小编sme*_*oks的帖子

char* 上的 free() 被 valgrind 识别为无效

我试图释放 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],我是否应该能够使用相同的语法通过将函数调用从 切换 …

c malloc free valgrind pointers

1
推荐指数
1
解决办法
94
查看次数

标签 统计

c ×1

free ×1

malloc ×1

pointers ×1

valgrind ×1