0

几天前我刚开始用 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    
4

2 回答 2

1

fgets返回NULL错误或 EOF。检查那个不是EOF.

while(fgets(line, 1024, fp) != NULL){
于 2012-05-31T16:43:10.487 回答
1

如果输入文件始终有效,我看不出有什么问题。我尝试在我的 Mac 上编译和运行它,它工作得非常好。也许您可以将示例文件上传到某个地方,这样我们就可以确切地看到发生了什么,因为memmove部分代码对于无效输入(例如空行或短行)来说太脆弱了。我建议将其更改为

char* data = line;
size_t len = strlen(line);
if (len > 3) {
    line[len - 3] = '\0';
    data++;
}

char *str_ptr;
str_ptr = strtok(data, ",");
for(; str_ptr != NULL ;){
    fprintf(stdout, "%s\n", str_ptr);
    str_ptr = strtok(NULL, ",");
}

我的代码离完美的数据验证还很远,但至少它不会在空行上抛出段错误。

于 2012-06-01T02:16:41.123 回答