1

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; 
wjtwise
  • 19
  • 6
  • malloc and calloc assigns you a new pointer each time you call it. So you aren't re-using a pointer. You're getting an entirely new address value assigned to x. In other words, the value of `int* x` changes every time you invoke calloc. With the latter two examples provided above, you are good. – selbie Mar 15 '23 at 00:18
  • Or to put it succinctly, `x` is an entirely new pointer each time you malloc/calloc. – selbie Mar 15 '23 at 00:19
  • 1
    you can reuse a pointer *variable*, what you cannot do is access the same memory location that was pointed at after you have freed that location. – pm100 Mar 15 '23 at 00:21
  • 1
    The concept of calling `malloc` "on a pointer" is meaningless. You don't pass it a pointer. It returns a pointer. Whether you choose to assign the returned pointer to a variable that you previously used for something else is entirely up to you. Your question seems to be "Can I reuse pointer variables?" And the answer is "Yes, of course you can." – Tom Karzes Mar 15 '23 at 00:26
  • if anyone thinks the question was decent, please upvote. I'm poor in rep. – wjtwise Mar 15 '23 at 00:33

1 Answers1

1

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);
    }
}
0___________
  • 60,014
  • 4
  • 34
  • 74