简体   繁体   中英

Freeing dynamically allocated memory to two pointers

I have two pointers, p1 and p2, which both point to a dynamically allocated piece of memory - let's just say it's an array of int with size 16.

    p1 = (int *)malloc(sizeof(int) * 16);
    p2 = p1;

If I do free(p1) , does it keep the dynamically allocated memory in tact since p2 is also referring to it, or does it just deallocate the memory, and the pointers become useless (assuming we enter new data there).

Short answer: it deallocates the memory and the pointers point to a non-allocated memory address.

A bit of context: In C, the dynamic allocation of memory and the fact that the memory is referenced by a pointer are unrelated. You can have a piece of memory allocated but not referenced by any pointer (this is called memory leak and it is bad because you won't be able to deallocate it), and you can have a pointer that points to a memory address which is not allocated.

Another topic is how this works for languages in which you don't allocate and deallocate explicitly the dynamic memory but this task is delegated to a garbage collector : in this case, it may be possible that the garbage collector would not deallocate that memory space because you are referencing it with another pointer, so you may still be wanting to use that data (but it depends on the logic of the garbage collector ).

It becomes useless. In the manual of free , it says:

The free() function frees the memory space pointed to by ptr , which must have been returned by a previous call to malloc() , calloc() , or realloc() . Otherwise, or if free(ptr) has already been called before, undefined behavior occurs. If ptr is NULL , no operation is performed.

You can see that free has got nothing to do with the pointer itself, but with the piece of memory it's pointing to, so if you use free over p1 , the other pointer will point to memory that has been freed, which means that it is useless.

If you free p1 then your memory is released and is no longer available to be used. Any copy of p1 is also invalid, even though it still points to the same location, just like p1 itself is not changed, but still invalid to be used.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM