[英]attempt to free memory causes error
I have declared the following struct: 我声明了以下结构:
typedef struct _RECOGNITIONRESULT {
int begin_time_ms, end_time_ms;
char* word;
} RECOGNITIONRESULT;
There is a method that creates an array of RECOGNITIONRESULT and fills it (for test purposes only): 有一种方法可以创建一个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");
}
}
The method to free memory is: 释放内存的方法是:
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);
}
}
The main method calls those methods like this: main方法调用如下方法:
int main(int argc, char** argv)
{
int count = 10;
RECOGNITIONRESULT *p = NULL;
test_realloc(&p,count);
free_realloc(p,count);
return 0;
}
Then if I try to free the memory allocated for "word", I get the following error: 然后,如果我尝试释放为“ word”分配的内存,则会出现以下错误:
HEAP CORRUPTION DETECTED: after normal block (#63) at 0x003D31D8. 已检测到堆损坏:在正常块(#63)之后的0x003D31D8。 CRT detected that the application wrote to memory after end of heap buffer.
CRT检测到应用程序在堆缓冲区结束后写入了内存。
Using the debugger I've discovered that the crash occurs when calling free(p[i].word); 使用调试器,我发现调用free(p [i] .word);时会发生崩溃。
What am I doing wrong? 我究竟做错了什么? How can I free he memory for the strings?
我如何释放他的琴弦记忆?
The problem is in your allocation of memory for word
. 问题在于您为
word
分配内存。 strlen("hello"+1)
should be strlen("hello")+1
. strlen("hello"+1)
应该是strlen("hello")+1
。
Since you appear to allocate a whole array of structures in one strike 由于您似乎一次就可以分配整个结构数组
RECOGNITIONRESULT **p;
*p = (RECOGNITIONRESULT *)realloc(*p, count * sizeof(RECOGNITIONRESULT));
you can free them in one call to free() as well : 您也可以在一次调用free()中释放它们:
void free_realloc(RECOGNITIONRESULT *p, int count){
free(p);
}
And the strlen("hello"+1)
is also wrong, as detected by Chowlett. 而且,Chowlett检测到
strlen("hello"+1)
也是错误的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.