سؤال

I am trying to write a c program to monitor the temperatures of my processor. To test my program I read integers from a file using fscanf. To my surprise this does not work under certain conditions. I am using the following code:

#include <stdio.h>
#define CORECOUNT 3
int main()
{
    int c=0;
    int core[CORECOUNT]={0};
    FILE *cmd[CORECOUNT];
    for (c=0; c<=CORECOUNT; c++)    //read input and store it in 'core'
    {
        cmd[c]=fopen("testinput", "r");
        printf("c=%d\n", c);
        fscanf(cmd[c], "%d", &core[c]);
        printf("core[c]=%d, z=%d\n", core[c], c);
        fclose(cmd[c]);
    }
    for (c=0; c<=CORECOUNT; c++)   //print input
    {
        printf("core%d: %d ", c, core[c]);
    }
    printf("\n");
}

It compiles without an error. Everything works as expected until the third (and last) call of fscanf: then suddenly 'c' gets the value 42 (which 'core' should get actually):

c=0
core[z]=42, z=0
c=1
core[z]=42, z=1
c=2
core[z]=42, z=2
c=3
core[z]=1, z=42
Segmentation fault (core dumped)

The segmentation fault occurs because fclose tries to close cmd[42] which does not exist.

When using other values of 'CORECOUNT' (e.g. 4) everything works as expected. However, when using a number which has '11' as last two digits in binary (e.g. 3, 7, 11, 15, ...) the program will crash. When declaring another integer and setting it to '0' the program works as expected when 'CORECOUNT' has a value which has '11' as last two digits in binary. If this is not the case 'core' does sometimes get strange values (e.g. '15274000', which are not the same every time the program is executed).

Strange enough, this only happens in gcc 4.6.3, but not in gcc 4.8

Where is the error in my code? Or is it even something in the compiler (which I highly doubt)?

just for now I'll declare another variable ('tmp') and use it as index in the call of fscanf:

printf("c=%d\n", c);
tmp=c;
fscanf(cmd[c], "%d", &core[tmp]);

I'm sorry if there are any spelling/grammar errors; English is not my native language.

هل كانت مفيدة؟

المحلول

In your for loops, change c<=CORECOUNT to c<CORECOUNT You have declared arrays of size [CORECOUNT] thus when CORECOUNT is 3, you have elements [0], [1], [2]. Having c<=CORECOUNT in your for loop, you try to access element [3] so memory outside the array is being corrupted.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top