So, I know we shouldn’t try to access freed memory.
e.g.
int * x = calloc(10, sizeof(int));
free(x);
x[0] = 2; // results in data corruption
Most posts such as LINK say not to reuse pointers period. After calling free(), can I call malloc() (or calloc()) again on the same pointer? My understanding is that it will point to a new, unused section of memory now and be fine.
e.g.
int * x = calloc(10, sizeof(int));
free(x);
x = calloc(10, sizeof(int));
x[0] = 2;
what about if the previous memory location of the pointer is used by other variables now? e.g.
int * x = calloc(10, sizeof(int));
free(x);
... stuff happens here ...
x = calloc(10, sizeof(int));
x[0] = 2;
>Solution :
The pointer only stores the value returned by malloc and this function does not know anything about this pointer.
You can assign pointer as many times as you need with the value returned by the malloc function if you free previously stored value, otherwise you will have a memory leak.
void foo(void)
{
char *ptr;
for(size_t i = 0; i < 10000000; i++)
{
ptr = malloc(rand() % 1000000);
free(ptr);
}
}