为什么此循环遍历文件缓冲区会引发BAD ACCESS异常?

时间:2020-02-08 10:29:30

标签: c pointers file-io buffer

我已经选择了几个小时,无法弄清楚为什么循环会尝试访问超出范围的内存...。任何帮助将不胜感激!

int CountCharacters(FILE *fp, const char* filename){
    // Get file size
    fseek(fp, 0L, SEEK_END);
    long size = ftell(fp);
    if (size == -1){ perror("Failed: "); return 0;} 
    rewind(fp); //seek back to file's beginning

    // Allocate approrpiately sized buffer ( size + 1 for null-termination)
    char *buf = malloc(sizeof (char) * (size + 1)); 

    // Read the entire file into memory
    size_t newLen = fread(buf, sizeof(char), size, fp);
    if ( ferror( fp ) != 0 ) {
        fputs("Error reading file", stderr);
    } else {
        buf[newLen++] = '\0'; /* Just to be safe. */
    }

    //Try to get byte count from buffer
    int byte_count[256] = {0}; //initialize character counts to 0
    for (int i = 0; i < size; ++i){
        byte_count[(int) buf[i]]++; //BAD ACCESS ERROR HERE
    }

    /* Do something with byte_count here */

    return (1);
}

0 个答案:

没有答案