segmentation fault

Hi,

I am having this segmentation fault not in the following program, bt. in my lab program . My lab program is horrible long so cannot post it here bt. I am using the following logic in my program which is giving the segmentation fault. Bt. if I run this sample program as it is it dosen't give the error. It is freaking me out :frowning:

#include<stdio.h>
#include<string.h>
#include<stdlib.h>

void *fxn();
 
typedef struct coord{
    int x;
//    int y;
    }cord ;

int main()
{
void *pt;
cord a, *p;
int x2, y2;

pt =fxn();
p = &a;
p = pt;

printf(" %d ",p->x);
}

void *fxn()
{
cord b,*point;
point = &b;

int x1= 10, y1= 10;

point->x = x1;
// point->y = y1;
return(point);
}

thanks a tonn in advance.

I think that the main issue with that code is that fxn() returns a pointer to a variable that is local to fxn() itself, which is deallocated when the function returns.
There are other minor problems of course, and I guess this code is only aimed at practicing with C pointers, but your segmentation fault should disappear if you trying solving that problem.

bye

Yes, local variables like that and pointers to them don't remain valid after the function call they exist inside returns. That it works at all is simply a coincidence. Make a few more function calls and the memory pointed to will probably be overwritten with garbage.

The compiler is probably warning you about this mistake, but as a warning, not an error.

You should pass a pointer to that function instead of getting one from it. Don't let it give you its local variables, give yours to it; perfectly valid when done before your function returns.

void fn(int *val)
{
       (*val)=3;
}

int main(void)
{
        int n;

        fn(&n);

        printf("n=%d\n", n);

        return(0);
}

You could also use a static variable, like:

int *fn(void)
{
       static int n;

        n=3;
        return(&n);
}

But this has several caveats. Static variables act like global variables; it will be pointing to the same pointer every time, so you can't keep the pointer around and expect the value to stay the same when other things use it. Also, this isn't thread-safe since multiple threads would be competing for the same variable. Probably best to pass a pointer.

1 Like

Thanks a lotttt...it works wonders :):b: