1

I've been picking at this for hours and can't figure out why the loop would try to access out of bounds memory.... Any help would be super appreciated!

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);
}
Adi Shah
  • 11
  • 2
  • 3
    What if declare buf as `unsigned char *buf` ? – Renat Feb 08 '20 at 10:35
  • 2
    Did you check the value of `buf[i]` when the access error occurs? – kaylum Feb 08 '20 at 10:36
  • @Renat Wow it looks like that did the trick! Does that mean the bad access was coming from the byte_count array, and not the buf? – Adi Shah Feb 08 '20 at 10:42
  • 1
    Does this answer your question? [What is an unsigned char?](https://stackoverflow.com/questions/75191/what-is-an-unsigned-char) Essentially, buf contained negative numbers, which you were then using as an index into byte_count – Korosia Feb 08 '20 at 10:49
  • 1
    For better debugging, you could split the line into separate instructions. This way you will see exactly, where something goes wrong. And you could insert `printf()` or `assert()` or anthing you see fit to debug. – the busybee Feb 08 '20 at 14:31
  • Please post a [mcve] so we can reproduce the problem – user3629249 Feb 09 '20 at 05:13

0 Answers0