简体   繁体   English

在C中分配的指针上进行malloc安全吗?

[英]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. 我正在使用C库,并且正在对内存管理非常谨慎。 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. 我不确定free(x)是否必要。

There is no such thing as an allocated pointer. 没有分配指针。

char *x = (char *) malloc(12); declares a pointer x . 声明一个指针x Then it allocates 12 bytes of memory and makes x point to the 12 bytes of memory. 然后,它分配12个字节的内存,并使x指向12个字节的内存。

free(x); frees the 12 bytes of memory. 释放12个字节的内存。 x still points to the 12 bytes of memory which are now freed. x仍指向现在已释放的12个字节的内存。

x = (char *) malloc(12); allocates another 12 bytes of memory and makes x point to the new 12 bytes of memory. 分配另外12个字节的内存,并使x指向新的12个字节的内存。

If you removed free(x); 如果删除了free(x); then you would be allocating 2 lots of 12 bytes of memory, and not freeing the first lot. 那么您将分配2个12字节的内存批次,而不释放第一批内存。 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. 是的,需要free(x) If you remove that you will definitely leak memory when you next malloc(12) . 如果删除它,那么当您下次执行malloc(12)时,肯定会泄漏内存。 Now if the sizes are really identical, then I question whether you really need that second malloc . 现在,如果大小确实相同,那么我质疑您是否真的需要第二个malloc If the sizes differ, you could use realloc() and remove the free . 如果大小不同,则可以使用realloc()并删除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. 但是,如果您没有保存第一个malloc()给出的地址,则会泄漏内存,因为在以后的某个时候应该是free() d。

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() ) 如果不这样做的free()并不危险,但你不能从这种状态中恢复过来,因为你失去了参考,其中的内存块是内存,所以你不能稍后返回它(它是由要求 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. 如果您不控制返回给您的内存,而您的程序执行了这种行为,那么您最终可能会吃光进程可用的所有内存,这可能会影响整个系统。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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