Почему эта l oop итерация по файловому буферу вызывает исключение BAD ACCESS? - PullRequest
1 голос
/ 08 февраля 2020

Я часами ковыряюсь в этом и не могу понять, почему l oop попытается получить доступ за пределами памяти .... Любая помощь будет очень признательна!

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);
}
...