C语言错误: HEAP CORRUPTION DETECTED
#define _CRT_SECURE_NO_WARNINGS
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
#define WORDMAX 3
struct dictsb
{
char * word;
char * trans;
};
typedef struct dictsb dic;
int main()
{
//开辟堆空间
dic * p = (dic*)malloc(sizeof(dic) * WORDMAX);
//读取文件内容
FILE * fp = fopen("E:\\dict_3.txt", "r");
if (!fp)
return -1;
int i = 0;
char buf[1024];
while (!feof(fp))
{
memset(buf, 0, 1024);
fgets(buf, 1024, fp);
//开辟堆空间
p[i].word = (char *)malloc(strlen(buf+1));
memset(p[i].word, 0, strlen(buf)+1);
strcpy(p[i].word, buf);
memset(buf, 0, 1024);
fgets(buf, 1024, fp);
int transLength = strlen(buf) + 1;
p[i].trans = (char*)malloc(transLength);
memset(p[i].trans, 0, transLength);
strcpy(p[i].trans, buf);
i++;
}
//关闭文件
fclose(fp);
printf("你好 世界 !开始测试free \n");
for (int i = 0; i < WORDMAX; i++)
{
free(p[i].word);
free(p[i].trans);
}
free(p);
system("pause");
return EXIT_SUCCESS;
}
解决方案
C语言错误: HEAP CORRUPTION DETECTED
把strlen(buf+1)
改成strlen(buf)+1
。