【发布时间】:2017-12-09 16:19:56
【问题描述】:
我想将使用malloc() 分配的pointers 存储在array 中,然后将它们全部存储在free 中。然而,即使程序没有抱怨它也不起作用。在cleanMemManager() 下面实际上不会是free 内存,因为在main() 内部测试时,char* pointer 不是NULL,它将打印???。
代码:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void **ptrList = NULL;
void tfree(void** ptr)
{
free(*ptr);
*ptr = NULL;
}
void* talloc(int size)
{
void* ptr = malloc(size);
ptrList[0] = ptr; ///No clue if this actually does what I think it does
return ptrList[0];
}
void initMemManager()
{
ptrList = (void**)malloc(sizeof(void**) * 3);
memset(ptrList, 0, sizeof(void**) * 3);
}
void cleanMemManager()
{
tfree(&ptrList[0]); //Doesn't free the right pointer it seems
}
int main()
{
initMemManager();
char* ptr = (char*)talloc(3);
cleanMemManager();
if (ptr != NULL) //This will trigger and I'm not expecting it to
printf("???");
getchar();
return 0;
}
我不明白用于此的语法,指针实际上根本没有被触及吗?既然它没有抛出任何错误,那么它释放了什么?
【问题讨论】:
-
关于:
void* ptr = malloc(size);1) 始终检查 (!=NULL) 返回值以确保操作成功。 2) 函数malloc()需要一个类型为size_t而不是int的参数。 (此隐式转换可能会失败,因为size_t未签名而int已签名。)
标签: c arrays pointers memory-management malloc