int *a = malloc(40);
int *b;
b=a;
if( *some conditions* )
free(a);
// I know that 'a' has been allocated this chunk of memory X times
// and free(a) has been called less than X times.
Run Code Online (Sandbox Code Playgroud)
我不知道那个条件,所以不知道'a'是否已被释放!那么现在我怎么能确定'b'即'a'是否已被释放.
如果要确保free对指向动态分配的内存的指针的后续调用不会造成任何损害,则应分配NULL给该指针.因为(重点补充):
free()函数释放ptr指向的内存空间,该内存空间必须由之前调用malloc(),calloc()或realloc()返回.否则,或者如果之前已经调用了free(ptr),则会发生未定义的行为.如果ptr为NULL,则不执行任何操作.
如果你想确保指针b总是引用另一个指针所a指向的同一个对象,你可以转而b使用指针a(并在每次需要使用它时取消引用它):
#include <stdio.h>
#include <stdlib.h>
int main() {
/* dynamically allocate some memory */
int *a = malloc(40);
/* b is a pointer to a pointer to an int */
int **b;
/* make b point to a */
b = &a;
if ( 1 ) {
/* free memory and assign NULL to the pointer */
free(a);
a = NULL;
}
/* nothing bad will happen when we dereference b now */
printf("%p\n", *b);
/* nothing bad will happen when we free the memory region
where the pointer b points to points to */
free(*b);
}
Run Code Online (Sandbox Code Playgroud)
内存泄漏的另一件事.双重释放内存时,没有内存泄露.在这种情况下,您将偶然发现未定义的行为,在这种情况下,任何事情都可能发生.仅仅因为你不会访问不属于你自己的内存区域(参见这篇伟大的文章).相反,当您松开对动态分配的内存块的引用时,您将泄漏内存.例如:
/* allocate some memory */
int *a = malloc(40);
/* reassign a without free-ing the memory before : you now have leaked memory */
a = malloc(40);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
5175 次 |
| 最近记录: |