几天前我刚开始用 C 编程。我的程序打开一个文件,逐行读取它,然后删除我不需要的东西(括号、换行符等),然后一旦我有了逗号分隔格式的数据,我想将它添加到数组中(然后将该数组添加到数组数组中)。我正在对逗号分隔的字符串进行标记,但是EXC_BAD_ACCESS, Could not access memory.
当我在调试器中运行它时,我不断得到它。
我究竟做错了什么?这是给我问题的代码部分:
//now data(variable: line) looks like this: 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 2, 2, 4
char *str_ptr;
str_ptr = strtok(line, ",");
for(; str_ptr != NULL ;){
fprintf(stdout, "%s\n", str_ptr);
str_ptr = strtok(NULL, ",");
}
这是我的整个代码:
#include <stdio.h>
int main() {
char line[1024];
FILE *fp = fopen("/Users/me/Desktop/output.txt","r");
printf("Starting.. \n");
if( fp == NULL ) {
return 1;
}
int count = 0;
int list[30]; //items will be stored here
while(fgets(line, 1024, fp) != EOF) {
count++;
//parse the text in the line Remove the open bracket, then remove the last newline,comma and close bracket
// data looks like this: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 2, 2, 4],
size_t len = strlen(line);
memmove(line, line+1, len-4);
line[len-4] = 0;
printf("%s \n",line);
//parse the numbers in the char
//now data looks like this: 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 2, 2, 4
char *str_ptr;
str_ptr = strtok(line, ",");
for(; str_ptr != NULL ;){
fprintf(stdout, "%s\n", str_ptr);
str_ptr = strtok(NULL, ",");
}
//for testing just stop the file after two lines
if (count == 2) {
break;
}
if ( count > 1000000) {
printf("count is higher than 1,000,000 \n");
count = 0;
}
}
printf(" num of lines is %i \n", count);
return 0;
}
除了调试器,我不确定在这种情况下如何获取有意义的信息。
更新
抱歉,不知道该怎么做。这是调试器中堆栈的副本(除了 main,如果我单击它们,它们都会说“没有可用的源代码..”然后列表中的项目:
Thread [1] (Suspended : Signal : EXC_BAD_ACCESS:Could not access memory)
strlen() at 0x7fff875ef4f0
__vfprintf() at 0x7fff875908c3
vfprintf_l() at 0x7fff8758f18e
fprintf() at 0x7fff87598d9a
main() at learningC.c:77 0x100000d5a