Thread: Unable to access/modify desired pointer value after calling a library function

  1. #1
    Registered User
    Join Date
    Apr 2016
    Posts
    10

    Unable to access/modify desired pointer value after calling a library function

    I'm using an external library https://people.sc.fsu.edu/~jburkardt/c_src/jacobi_eigenvalue/jacobi_eigenvalue.c to calculate eigenvalue of a matrix. However, after calling the library function, I received Segmentation fault when I tried to access desired pointer values.

    Code:
    #define M 3
    double Gyration[M*M] = { 
              gyration[0][0],gyration[0][1],gyration[0][2], 
              gyration[1][0],gyration[1][1],gyration[1][2],
              gyration[2][0],gyration[2][1],gyration[2][2] };
    
    jacobi_eigenvalue(M, Gyration, it_max, v, d, &it_num, &rot_num);
    rog = sqrt(d[0]+d[1]+d[2]);  
    *Denominator= 2*pow(rog,4); 
    *Nominator= pow((d[2]-d[1]),2)+pow((d[2]-d[0]),2)+pow((d[1]-d[0]),2);
    * Asp = (*Nominator)/(*Denominator);
    # undef M
    Denominator, Nominator, and Asp were defined as double variables in main function and passed as pointers. However I received segmentation fault when I was trying to access them after library function call.
    I guess the issue is dereferencing a pointer that has been freed since in the library function, malloc is used. But, I am not sure where exactly the issue is and how to fix it.
    Thank you in advance.

  2. #2
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    28,413
    It looks like Denominator, Nominator, and Asp have nothing to do with the library function call, so perhaps the mistake lies elsewhere. I suggest that you post the smallest and simplest compilable program that demonstrates the error, e.g., a main function to setup the values and call your function, and then your function that calls the library function.
    Quote Originally Posted by Bjarne Stroustrup (2000-10-14)
    I get maybe two dozen requests for help with some sort of programming or design problem every day. Most have more sense than to send me hundreds of lines of code. If they do, I ask them to find the smallest example that exhibits the problem and send me that. Mostly, they then find the error themselves. "Finding the smallest program that demonstrates the error" is a powerful debugging tool.
    Look up a C++ Reference and learn How To Ask Questions The Smart Way

  3. #3
    Registered User
    Join Date
    Apr 2016
    Posts
    10
    That's correct that these three variables have no relation with the library function. But I am able to access *Denominator, *Nominator, and *Asp (which are 0) before the function call.

  4. #4
    Registered User
    Join Date
    Sep 2014
    Posts
    364
    Quote Originally Posted by xy127 View Post
    I'm using an external library https://people.sc.fsu.edu/~jburkardt/c_src/jacobi_eigenvalue/jacobi_eigenvalue.c to calculate eigenvalue of a matrix. However, after calling the library function, I received Segmentation fault when I tried to access desired pointer values.

    Code:
    #define M 3
    double Gyration[M*M] = { 
              gyration[0][0],gyration[0][1],gyration[0][2], 
              gyration[1][0],gyration[1][1],gyration[1][2],
              gyration[2][0],gyration[2][1],gyration[2][2] };
    
    jacobi_eigenvalue(M, Gyration, it_max, v, d, &it_num, &rot_num);
    rog = sqrt(d[0]+d[1]+d[2]);  
    *Denominator= 2*pow(rog,4); 
    *Nominator= pow((d[2]-d[1]),2)+pow((d[2]-d[0]),2)+pow((d[1]-d[0]),2);
    * Asp = (*Nominator)/(*Denominator);
    # undef M
    Denominator, Nominator, and Asp were defined as double variables in main function and passed as pointers. However I received segmentation fault when I was trying to access them after library function call.
    What i have found in the internet is this declaration:
    Code:
    void jacobi_eigenvalue (int n, double a[], int it_max, double v[], double d[], int &it_num, int &rot_num);
    Edit: Ooops, i see you have post the link to the library. I think I need more coffee.
    This give me a few questions.
    From where come your variable 'it_max' and is it of type int?
    From where come your variable 'v' and is it an array of type double (and has the array the right size)?
    From where come your variable 'd' and is it an array of type double (and has the array the right size)?
    From where come your variable 'it_num' and is it of type int?
    From where come your variable 'rot_num' and is it of type int?

    You can output all values with printf before you call the function.

    Quote Originally Posted by xy127 View Post
    I guess the issue is dereferencing a pointer that has been freed since in the library function, malloc is used. But, I am not sure where exactly the issue is and how to fix it.
    Thank you in advance.
    No! A function will never free a pointer. If you write functions, also never free pointers. The function doesn't know if the pointer point to a malloc'ed memory or to a local variable or struct.
    Last edited by WoodSTokk; 07-09-2016 at 06:47 PM.
    Other have classes, we are class

  5. #5
    Registered User
    Join Date
    Apr 2016
    Posts
    10
    1. I defined It_max(max number of iterations) as int it_max=100 in my own function(not the library function) which is not shown above.
    2. 'v' is a double type vector that stores eigenvectors. I defined 'v' as double v[M] where M=3 in my function.
    3. 'd' is a double type vector that stores eigenvalues. I defined d as double d[M]
    4. it_num and rot_num are both defined as integer type in my function
    5. There shows no error when gdb passes the library function. And I was able to access v[] and d[] ( The output of library function)

  6. #6
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,662
    > 2. 'v' is a double type vector that stores eigenvectors. I defined 'v' as double v[M] where M=3 in my function.
    Whereas the comment in the library code reads

    > Output, double V[N*N], the matrix of eigenvectors.

    It seems to me that your supplied v array is far too small, and the library scribbles over memory it shouldn't.
    The result is typically a segfault, when the real owner of the memory finds it's been trashed.
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.

  7. #7
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    28,413
    Quote Originally Posted by xy127
    That's correct that these three variables have no relation with the library function. But I am able to access *Denominator, *Nominator, and *Asp (which are 0) before the function call.
    That does not mean that the problem lies with the library function call. The problem could lie with your code, e.g., code that you did not show that results in undefined behaviour, but only surfaced after the library function call was made. This is why I suggested that you come up with the smallest and simplest compilable program that demonstrates the error: in the process of doing so, you may discover the problem, and if you don't, you would have ruled out code that is irrelevant to the problem.

    Even if you don't want to do what I recommended for whatever reason, at the very least you could try:
    Code:
    #define M 3
    double Gyration[M*M] = { 
              gyration[0][0],gyration[0][1],gyration[0][2], 
              gyration[1][0],gyration[1][1],gyration[1][2],
              gyration[2][0],gyration[2][1],gyration[2][2] };
     
    /*jacobi_eigenvalue(M, Gyration, it_max, v, d, &it_num, &rot_num);*/
    printf("%f %f %f\n", *Denominator, *Nominator, *Asp);
    # undef M
    Does the above result in zeroes being printed to standard output? If so, uncomment the previous line. What happens? If you then get a segmentation fault, then you need to do what I recommended, because then all I can tell you is that either the mistake lies in your code (that I cannot see because you did not provide it) or the mistake lies in jacobi_eigenvalue, but even if I were interested in doing so, I am not about to spend time to try and debug jacobi_eigenvalue when the mistake could reasonably lie in your code.
    Quote Originally Posted by Bjarne Stroustrup (2000-10-14)
    I get maybe two dozen requests for help with some sort of programming or design problem every day. Most have more sense than to send me hundreds of lines of code. If they do, I ask them to find the smallest example that exhibits the problem and send me that. Mostly, they then find the error themselves. "Finding the smallest program that demonstrates the error" is a powerful debugging tool.
    Look up a C++ Reference and learn How To Ask Questions The Smart Way

  8. #8
    Registered User
    Join Date
    Apr 2016
    Posts
    10
    Quote Originally Posted by Salem View Post
    > 2. 'v' is a double type vector that stores eigenvectors. I defined 'v' as double v[M] where M=3 in my function.
    Whereas the comment in the library code reads

    > Output, double V[N*N], the matrix of eigenvectors.

    It seems to me that your supplied v array is far too small, and the library scribbles over memory it shouldn't.
    The result is typically a segfault, when the real owner of the memory finds it's been trashed.
    Sorry, I had a typo in previous reply. 'v' is defined as double v[M*M]. 'v' has same size as gyration matrix

  9. #9
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,662
    Quote Originally Posted by xy127 View Post
    Sorry, I had a typo in previous reply. 'v' is defined as double v[M*M]. 'v' has same size as gyration matrix
    So how do we know there aren't any other "typos" masquerading as facts in your posts?

    Short, Self Contained, Correct Example
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.

  10. #10
    Registered User
    Join Date
    Apr 2016
    Posts
    10
    Quote Originally Posted by Salem View Post
    So how do we know there aren't any other "typos" masquerading as facts in your posts?

    Short, Self Contained, Correct Example
    I apologize for that mistake. But if it was v[M], then error will occur inside library function since the input is not in correct form.

  11. #11
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    28,413
    No worries. So, where's the code?
    Quote Originally Posted by Bjarne Stroustrup (2000-10-14)
    I get maybe two dozen requests for help with some sort of programming or design problem every day. Most have more sense than to send me hundreds of lines of code. If they do, I ask them to find the smallest example that exhibits the problem and send me that. Mostly, they then find the error themselves. "Finding the smallest program that demonstrates the error" is a powerful debugging tool.
    Look up a C++ Reference and learn How To Ask Questions The Smart Way

  12. #12
    Registered User
    Join Date
    Apr 2016
    Posts
    10
    Thanks !

    I'm posting the entire function. The code itself contains at least 20 functions. This function is independent with others. So I am not going to post all the code.

    Code:
    void asphericity(particle *p, int N, float aveLTail[MAX2][MAX2], double &Nominator, double &Denominator, double *Asp ,double *cmx, double *cmy, double *cmz){
        int i, j, k,m,n,M;
        double x[10000];
        double y[10000];
        double z[10000];
        double *Q;
        double gyration[3][3];
        double v[M*M];
        double d[M];
        float ut, up;
        float bs;
        double hdistance;
        double tdistance;
        double rog; 
        int hcount=0;
        int tcount=0;
        int it_max;
        int it_num;
        int rot_num;
        double hx=0;
        double hy=0;
        double hz=0;
        double tx=0;
        double ty=0;
        double tz=0;
        m=0;
        Nominator=NULL;
        Denominator=NULL;
       
        it_max=100;
        for(i = 1; i<=N; i++) {
           if (p[i].mol == p[i-1].mol){
               if (p[i-1].type==1 ||p[i-1].type==2 || p[i-1].type==3 || p[i-1].type==6){
                    hcount++;
                    hx += p[i-1].x;
                    hy += p[i-1].y;
                    hz += p[i-1].z;
               }
               else if (p[i-1].type==4 && p[i-2].type==9){
                    tcount++;
                    tx += p[i-1].x;
                    ty += p[i-1].y;
                    tz += p[i-1].z;
                    hcount += 2;
                    hx += p[i-2].x+p[i-3].x;
                    hy += p[i-2].y+p[i-3].y;
                    hz += p[i-2].z+p[i-3].z;
                }  
               else if (p[i-1].type==4 && p[i-2].type!=9){
                    tcount++;
                    tx += p[i-1].x;
                    ty += p[i-1].y;
                    tz += p[i-1].z;
               }
                    
           }
           else if (p[i].mol != p[i-1].mol && p[i-1].mol!=0) {
                    tcount++;
                    tx += p[i-1].x;
                    ty += p[i-1].y;
                    tz += p[i-1].z;
                   (hx) /= hcount; /*geometric center of head beads*/
                   (hy) /= hcount;
                   (hz) /= hcount;
                   (tx) /= tcount;
                   (ty) /= tcount;
                   (tz) /= tcount;
                   hcount=0;
                   tcount=0;
                   hdistance=sqrt(pow((hx-*cmx),2)+pow((hy-*cmy),2)+pow((hz-*cmz),2));
                   tdistance=sqrt(pow((tx-*cmx),2)+pow((ty-*cmy),2)+pow((tz-*cmz),2));
                   if(hdistance>tdistance){
                      x[m]=hx;
                      y[m]=hy;
                      z[m]=hz;
                      m++;
                     }
                   hx=0;
                   hy=0;
                   hz=0;
                   tx=0;
                   ty=0;
                   tz=0;
                 }              
           } 
        
    
        for(j = 0; j<m; j++) {
            gyration[0][0]+= pow((x[j]-*cmx),2);
            gyration[0][1]+=(x[j]-*cmx)*(y[j]-*cmy);
            gyration[0][2]+=(x[j]-*cmx)*(z[j]-*cmz); 
            gyration[1][0]+=(y[j]-*cmy)*(x[j]-*cmx);
            gyration[1][1]+=pow((y[j]-*cmy),2);
            gyration[1][2]+=(y[j]-*cmy)*(z[j]-*cmz);
            gyration[2][0]+=(z[j]-*cmz)*(x[j]-*cmx);
            gyration[2][1]+=(z[j]-*cmz)*(y[j]-*cmy);
            gyration[2][2]+=pow((z[j]-*cmz),2);
         }
        for(i =0; i<3; i++){
           for(j=0; j<3; j++){
               gyration[i][j]/=m;
              }
        }
    
     #define M 3
        double Gyration[M*M] = { 
                  gyration[0][0],gyration[0][1],gyration[0][2], 
                  gyration[1][0],gyration[1][1],gyration[1][2],
                  gyration[2][0],gyration[2][1],gyration[2][2] };
    
        jacobi_eigenvalue(M, Gyration, it_max, v, d, &it_num, &rot_num);
         double *Nominator;
         double *Denominator;
        rog = sqrt(d[0]+d[1]+d[2]);  
        *Denominator= 2*pow(rog,4); 
        *Nominator= pow((d[2]-d[1]),2)+pow((d[2]-d[0]),2)+pow((d[1]-d[0]),2);
        * Asp = (*Nominator)/(*Denominator);
    # undef M
     }

  13. #13
    Registered User
    Join Date
    Apr 2016
    Posts
    10
    Quote Originally Posted by laserlight View Post
    No worries. So, where's the code?
    Please ignore the previous code. I made some modification based on your suggestion. The first printf prints all three variables 0. But Segmentation fault appears at send printf. So, something is wrong with the library function.

    Code:
    void asphericity(particle *p, int N, float aveLTail[MAX2][MAX2], double *Nominator, double *Denominator, double *Asp ,double *cmx, double *cmy, double *cmz){
        int i, j, k,m,n,M;
        double x[10000];
        double y[10000];
        double z[10000];
        double *Q;
        double gyration[3][3];
        double v[M*M];
        double d[M];
        float ut, up;
        float bs;
        double hdistance;
        double tdistance;
        double rog; 
        int hcount=0;
        int tcount=0;
        int it_max;
        int it_num;
        int rot_num;
        double hx=0;
        double hy=0;
        double hz=0;
        double tx=0;
        double ty=0;
        double tz=0;
        m=0;
    
       
        it_max=100;
        for(i = 1; i<=N; i++) {
           if (p[i].mol == p[i-1].mol){
               if (p[i-1].type==1 ||p[i-1].type==2 || p[i-1].type==3 || p[i-1].type==6){
                    hcount++;
                    hx += p[i-1].x;
                    hy += p[i-1].y;
                    hz += p[i-1].z;
               }
               else if (p[i-1].type==4 && p[i-2].type==9){
                    tcount++;
                    tx += p[i-1].x;
                    ty += p[i-1].y;
                    tz += p[i-1].z;
                    hcount += 2;
                    hx += p[i-2].x+p[i-3].x;
                    hy += p[i-2].y+p[i-3].y;
                    hz += p[i-2].z+p[i-3].z;
                }  
               else if (p[i-1].type==4 && p[i-2].type!=9){
                    tcount++;
                    tx += p[i-1].x;
                    ty += p[i-1].y;
                    tz += p[i-1].z;
               }
                    
           }
           else if (p[i].mol != p[i-1].mol && p[i-1].mol!=0) {
                    tcount++;
                    tx += p[i-1].x;
                    ty += p[i-1].y;
                    tz += p[i-1].z;
                   (hx) /= hcount; /*geometric center of head beads*/
                   (hy) /= hcount;
                   (hz) /= hcount;
                   (tx) /= tcount;
                   (ty) /= tcount;
                   (tz) /= tcount;
                   hcount=0;
                   tcount=0;
                   hdistance=sqrt(pow((hx-*cmx),2)+pow((hy-*cmy),2)+pow((hz-*cmz),2));
                   tdistance=sqrt(pow((tx-*cmx),2)+pow((ty-*cmy),2)+pow((tz-*cmz),2));
                   if(hdistance>tdistance){
                      x[m]=hx;
                      y[m]=hy;
                      z[m]=hz;
                      m++;
                     }
                   hx=0;
                   hy=0;
                   hz=0;
                   tx=0;
                   ty=0;
                   tz=0;
                 }              
           } 
        
    
        for(j = 0; j<m; j++) {
            gyration[0][0]+= pow((x[j]-*cmx),2);
            gyration[0][1]+=(x[j]-*cmx)*(y[j]-*cmy);
            gyration[0][2]+=(x[j]-*cmx)*(z[j]-*cmz); 
            gyration[1][0]+=(y[j]-*cmy)*(x[j]-*cmx);
            gyration[1][1]+=pow((y[j]-*cmy),2);
            gyration[1][2]+=(y[j]-*cmy)*(z[j]-*cmz);
            gyration[2][0]+=(z[j]-*cmz)*(x[j]-*cmx);
            gyration[2][1]+=(z[j]-*cmz)*(y[j]-*cmy);
            gyration[2][2]+=pow((z[j]-*cmz),2);
         }
        for(i =0; i<3; i++){
           for(j=0; j<3; j++){
               gyration[i][j]/=m;
              }
        }
    
     #define M 3
        double Gyration[M*M] = { 
                  gyration[0][0],gyration[0][1],gyration[0][2], 
                  gyration[1][0],gyration[1][1],gyration[1][2],
                  gyration[2][0],gyration[2][1],gyration[2][2] };
        printf("%.6f\t%.6f\t%.6f\n", *Denominator, *Nominator, *Asp);
        jacobi_eigenvalue(M, Gyration, it_max, v, d, &it_num, &rot_num);
        printf("%.6f\t%.6f\t%.6f\n", *Denominator, *Nominator, *Asp);
        rog = sqrt(d[0]+d[1]+d[2]);  
        *Denominator= 2*pow(rog,4); 
        *Nominator= pow((d[2]-d[1]),2)+pow((d[2]-d[0]),2)+pow((d[1]-d[0]),2);
        * Asp = (*Nominator)/(*Denominator);
    # undef M
     }

  14. #14
    Registered User
    Join Date
    Sep 2014
    Posts
    364
    Thats a good example for using desciptive names for variables and defines.
    Line 2:
    Code:
        int i, j, k,m,n,M;
    M is defined as an integer, but not inizialized.


    Line 8+9:
    Code:
        double v[M*M];
        double d[M];
    v and d are defined as double vectors with a size of M, but M isn't initialized.
    Nobody knows how big or small this vectors are.


    Line 104+105:
    Code:
    #define M 3
        double Gyration[M*M] = {
    …
    M is now a define to represent 3.
    And Gyration is a double vector in size of 9.
    But have v and d the right size?


    To fix this, set line 104 as the first line (in front of the function).
    Delete the integer M on line 2.
    To avoid confusion, rename M to SIZE_M. It makes it clear that this is a defined name.
    Last edited by WoodSTokk; 07-10-2016 at 02:20 PM.
    Other have classes, we are class

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Trying to modify array in a shared library function
    By JulietBoy in forum C Programming
    Replies: 8
    Last Post: 05-24-2013, 05:39 AM
  2. Replies: 3
    Last Post: 03-14-2013, 03:25 PM
  3. Replies: 7
    Last Post: 01-12-2013, 05:07 PM
  4. unable to access structure within a function
    By bluetxxth in forum C Programming
    Replies: 7
    Last Post: 02-17-2010, 03:52 AM
  5. Calling C function from dynamically loaded library
    By polas in forum Linux Programming
    Replies: 17
    Last Post: 09-02-2009, 01:04 PM

Tags for this Thread