I can't figure out why I am getting the error free(): invalid pointer
when running this code. I thought p
is going to point to a block of memory set aside for the structures, so I am trying to free pointers beginning from the p
e.g. p+1
, but this is no good. What am I missing here?
#include <stdio.h>
#include <stdlib.h>
struct s {
int x;
};
int main()
{
struct s *p = NULL;
for (int i = 0; i < 3; i++) {
if ((p = realloc(p, (i+1) * sizeof(struct s))) != NULL) {
struct s x = {.x=i*10};
*(p+i) = x;
} else exit(EXIT_FAILURE);
}
for (int i=0;i<3;i++) {printf("%d ", (p+i)->x);}
//free(p);
free(p+1);
//free(p+2);
return 0;
}
Before the loop you declared the pointer p
struct s *p = NULL;
So after the loop it will store the address of the last reallocated memory.
To free the allocated memory you need just to write
free( p );
The expression p + 1
points to the second element of the dynamically allocated array that was not allocated dynamically. It is the whole array that was allocated dynamically.