gpt4 book ai didi

C 通过函数对 char 进行 malloc/free 双指针

转载 作者:行者123 更新时间:2023-11-30 18:34:55 24 4
gpt4 key购买 nike

我已经阅读了这些链接:link1link2 .

但是,如果我在 valgrind 中执行以下代码:

valgrind --tool=memcheck --leak-check=full --num-callers=40 --show-possibly-lost=no

我可以看到内存没有正确释放。

#include <stdio.h>
#include <stdlib.h>

void printVector(char ** vector, int N);
void allocateVector(char *** vector, int N, int M);
void deallocateVector(char *** vector, int N);

int main(int argc, char * argv[]) {
char ** vector;
int N=6;
int M=200;
allocateVector(&vector,N,M);
printVector(vector,N);
deallocateVector(&vector,N);
}

void allocateVector(char *** vector, int N, int M) {
*vector=(char **) malloc(N*sizeof(char *));
int i;
for(i=0; i<N; i++) {
(*vector)[i]=(char *) malloc(M*sizeof(char));
(*vector)[i]="Empty";
}
}

void deallocateVector(char *** vector, int N) {
int i;
char ** temp=*vector;
for(i=0; i<N; i++) {
if(temp[i]!=NULL) {
free(temp[i]);
}
}
if(temp!=NULL) {
free(temp);
}
*vector=NULL;
}

我找不到错误在哪里。

最佳答案

问题出在这里:

for(i=0; i<N; i++) {
(*vector)[i]=(char *) malloc(M*sizeof(char));
(*vector)[i]="Empty";
}

您分配空间并将指向它的指针存储在(*vector)[i]中。然后用字符串常量“Empty”的地址覆盖该指针。

这会导致两个问题:

  • malloc 返回的内存已泄漏,因为您不再拥有对它的引用。
  • 当您稍后调用 free 时,您将向其传递字符串常量的地址,而不是已分配的内存块的地址。以这种方式调用 free 会调用 undefined behavior .

您需要使用strcpy函数将字符串常量复制到您分配的内存中:

for(i=0; i<N; i++) {
(*vector)[i]=malloc(M);
strcpy((*vector)[i],"Empty");
}

此外,don't cast the return value of malloc ,并且 sizeof(char) 定义为 1 并且可以省略。

关于C 通过函数对 char 进行 malloc/free 双指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49175183/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com