简体   繁体   中英

Is it safe to malloc on an allocated pointer in C?

I'm working on a C library and am trying to be very cautious about memory management. I have a function which allocates memory for a pointer, and am trying to cover the case in which the pointer is already allocated. I am wondering if I need to free the pointer before allocating over it.

char *x = (char *) malloc(12);
// ...
free(x);
x = (char *) malloc(12);

I'm unsure if the free(x) is necessary.

There is no such thing as an allocated pointer.

char *x = (char *) malloc(12); declares a pointer x . Then it allocates 12 bytes of memory and makes x point to the 12 bytes of memory.

free(x); frees the 12 bytes of memory. x still points to the 12 bytes of memory which are now freed.

x = (char *) malloc(12); allocates another 12 bytes of memory and makes x point to the new 12 bytes of memory.

If you removed free(x); then you would be allocating 2 lots of 12 bytes of memory, and not freeing the first lot. Whether that is a memory leak or not depends on how your program is supposed to work - it's only a memory leak if you aren't still using the memory for something.

Yes the free(x) is necessary. If you remove that you will definitely leak memory when you next malloc(12) . Now if the sizes are really identical, then I question whether you really need that second malloc . If the sizes differ, you could use realloc() and remove the free .

It is safe, that's to say: you are not incurring in any undefined behaviour. But you are leaking memory, in case you have not saved the address given by the first malloc() , as it should be free() d at some point later.

Not doing the free() is not dangerous, but you cannot recover from that state, as you lost the reference to the memory where that chunk of memory was, so you cannot return it later (it is required by free() )

If you don't control to return the memory you are given, and your program does this kind of behaviour, you can finally eat up all the memory available to your process, and this can impact your whole system.

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