Call to free() throwing segmentation fault Call to free() throwing segmentation fault unix unix

Call to free() throwing segmentation fault


You are freeing something not returned by malloc (q is never initialized). Also I can see you are doing

p++

In doing this, you are losing p and you can't free it anymore. Just in case you meant q=p, that's not valid either. You can only free what malloc returned.

EDIT

In light of comment it seems the OP does intend q = p. You can do this:

char *p;char *save_p;p = malloc(10); /* stop casting malloc */save_p = p; /* save the original value of p BEFORE altering it *//* use p to your heart's content */free(save_p); /* it's legal to free this */

I see you are asking something about char versus integer. It's the same:

You can only free the exact values returned by malloc.


You never initialize that q pointer you're freeing, that's why your program segfaults: it tries to free a random uninitialized pointer.


You do not initialize q to the area you malloc-ed, and then you trash p (doing p = q), too. You need to save your pointer to malloc-ed area in order to be able to free it. So something like

p = q = malloc(...);// play with p, or q, but not with bothfree( /* the one you have not played with */ );