gpt4 book ai didi

c - 尝试释放内存会导致错误

转载 作者:太空宇宙 更新时间:2023-11-04 06:40:06 25 4
gpt4 key购买 nike

我已经声明了以下结构:

typedef struct _RECOGNITIONRESULT {
int begin_time_ms, end_time_ms;
char* word;
} RECOGNITIONRESULT;

有一种方法可以创建一个 RECOGNITIONRESULT 数组并填充它(仅用于测试目的):

void test_realloc(RECOGNITIONRESULT** p, int count){
int i;
*p = (RECOGNITIONRESULT *)realloc(*p, count * sizeof(RECOGNITIONRESULT));
for (i = 0; i < count; i++){
(*p)[i].begin_time_ms = 2*i;
(*p)[i].end_time_ms = 2*i+1;
(*p)[i].word=(char *) malloc ( (strlen("hello"+1) * sizeof(char ) ));
strcpy((*p)[i].word,"hello");
}
}

释放内存的方法是:

void free_realloc(RECOGNITIONRESULT* p, int count){
int i = 0;
if(p != NULL){
if (count > 0){
for (i = 0; i < count; i++){
free(p[i].word); //THE PROBLEM IS HERE.
}
}
free(p);
}
}

main 方法调用这些方法是这样的:

int main(int argc, char** argv)
{
int count = 10;
RECOGNITIONRESULT *p = NULL;
test_realloc(&p,count);
free_realloc(p,count);
return 0;
}

然后如果我尝试释放分配给“word”的内存,我会收到以下错误:

检测到堆损坏:在 0x003D31D8 处的正常 block (#63) 之后。CRT 检测到应用程序在堆缓冲区结束后写入内存。

使用调试器我发现调用 free(p[i].word) 时会发生崩溃

我做错了什么?我怎样才能释放字符串的内存?

最佳答案

问题在于您为 word 分配的内存。 strlen("hello"+1) 应该是 strlen("hello")+1

关于c - 尝试释放内存会导致错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9806067/

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