我试图释放 char** 数组中存在的 char* 指针,但 valgrind 确定此操作无效。
这是我正在做的一个简单示例:
struct building{
int propertyPrice;
int totalArea;
char** floors;
}
int main(){
struct building* B = malloc(sizeof(struct building));
for(size_t i=0;i<10;i++)
B->floors[i] = malloc(20 * sizeof(char*));
}
Run Code Online (Sandbox Code Playgroud)
这就是我感到困惑的地方 - 我可以通过以下循环访问元素:
for(size_t i=0;i<10;i++)
printf("%s", B->floors[i]); //assume that a valid string exists at each floors[i]!
Run Code Online (Sandbox Code Playgroud)
我尝试按如下方式释放分配的内存:
for(size_t i=0;i<10;i++)
free(B->floors[i]);
free(B);
Run Code Online (Sandbox Code Playgroud)
请原谅缺少对 NULL 的 malloc() 检查,为了简洁起见,我将其删除。
Valgrind 确定该操作free(B->floors[i])是Invalid free() / delete / delete[] / realloc()。然而,如果我可以通过 访问各个 char* 元素B-floors[i],我是否应该能够使用相同的语法通过将函数调用从 切换 …