简体   繁体   English

malloc中的内存泄漏?

[英]memory leak in malloc?

I've got the following faulty piece of code in C and I am wondering if there will be a memory leak or if there will be a pointer which is pointing to a free memory location.我在 C 中有以下错误代码,我想知道是否会出现内存泄漏或者是否会有指向空闲内存位置的指针。

int* p = (int*) malloc(sizeof(int));
p = NULL;
free(p);

Yes it will leak memory.是的,它会泄漏内存。 You assign p to NULL before freeing the contents it's pointing to.在释放它指向的内容之前,您将 p 分配给 NULL。 One quick change will fix it:一个快速更改将修复它:

int* p = malloc(sizeof(int));
free(p);
p = NULL;

The difference here is we give free the address allocated by malloc before setting p to NULL.这里的区别是我们在将 p 设置为 NULL 之前释放了 malloc 分配的地址。 In general setting a pointer to NULL will not free the contents, but will allow you to check if the pointer is valid or not which can have a lot of practical applications.通常将指针设置为 NULL 不会释放内容,但可以让您检查指针是否有效,这可以有很多实际应用。

You will have a memory leak.你会有内存泄漏。

After you assign NULL to p , you no longer have a way to refer to the memory you allocated with malloc .NULL分配给p ,您将无法再引用使用malloc分配的malloc

Your call to free will try to free NULL , doing nothing.您对free调用将尝试释放NULL ,什么也不做。

The following will correctly free the memory:以下将正确释放内存:

int *p = malloc(sizeof(int));
free(p);
p = NULL;

Note that you don't need to set p to NULL after freeing, you only really need the first two lines.请注意,您不需要在释放后将p设置为NULL ,您只需要前两行。

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

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