我的程序在WinXp中的MINGW32上运行。该程序由gcc编译,并使用gdb调试工具获得预期的结果。但是当在MINGW32下直接运行它时,WinXp将报告错误:
“0x7c956a6e”指令引用了“0x00000000”的内存。此内存无法“读取”。
然后如何找到这条指令?我检查过它似乎是由malloc函数引起的。源代码如下:
int find(FILE *fp, char **head) {
char str[100];
char *p, c;
int i = 0, j = 0;
do {
c = fgetc(fp);
if(c == EOF)
return 0;
} while(c == ' ' || c == '\n');
while(c != ' ' && c != '\n') {
str[i++] = c;
c = fgetc(fp);
}
*head = (char *)malloc(sizeof(char) * i);
if(*head == NULL)
printf("\nCannot get memory (find)");
else {
p = *head;
for(j = 0; j < i; j++) {
*(p++) = str[j];
}
*p = '\0';
return 1;
}
return 0;
}
如果有人能提供帮助,我们将不胜感激!
10/7感谢您的评论。以下是代码的其余部分和数据模式:
int main()
{
FILE *fp;
int lines = 0, i = 0;
TianYa *yp, *linep;
char *head = NULL;
fp = fopen("tysample.txt", "r");
if(fp == NULL)
printf("\nCannot open file");
else {
yp = (TianYa *)malloc(TIAN_YA_LINES * sizeof(TianYa));
if(yp == NULL)
printf("\nCannot get memory (main)");
else {
linep = yp;
i = 0;
while(find(fp, &head) != 0) {
switch(i++) {
case 0:
linep->name = head;
break;
case 1:
linep->passwd = head;
break;
case 2:
linep->email = head;
i = 0;
linep++;
lines++;
break;
}
}
}
}
linep = yp;
for(i = 0; i < lines; i++) {
printf("\nName:%s, Passwd:%s, Email:%s", linep->name, linep->passwd, linep->email);
/* free(linep->name);
free(linep->passwd);
free(linep->email);
*/ linep++;
}
free(yp);
yp = NULL;
linep = NULL;
if(fclose(fp))
printf("\nFailed to close file");
return 0;
}
momre 123456 baitianyang@live.cn
白天也懂 123456 baitianyedong@tianya.cn
baitiansosuo weirenminfuwu baitianyouxiang@sohu.com
heng__chang 87732351 baitianyu.06@163.com
风正 5581100 baitianyu@126.com
sparkbai 20001228 baitianyu@tianya.cn
背粪篓进银行 19851019 baitianyu123@163.com
白天月 11200929 baitianyue@126.com