c - fscanf writes output in index of variable -


i trying write c program monitor temperatures of processor. test program read integers file using fscanf. surprise not work under conditions. using following code:

#include <stdio.h> #define corecount 3 int main() {     int c=0;     int core[corecount]={0};     file *cmd[corecount];     (c=0; c<=corecount; c++)    //read input , store 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]);     }     (c=0; c<=corecount; c++)   //print input     {         printf("core%d: %d ", c, core[c]);     }     printf("\n"); } 

it compiles without error. works expected until third (and last) call of fscanf: 'c' gets value 42 (which 'core' should 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 close cmd[42] not exist.

when using other values of 'corecount' (e.g. 4) works expected. however, when using number has '11' last 2 digits in binary (e.g. 3, 7, 11, 15, ...) program crash. when declaring integer , setting '0' program works expected when 'corecount' has value has '11' last 2 digits in binary. if not case 'core' strange values (e.g. '15274000', not same every time program executed).

strange enough, happens in gcc 4.6.3, not in gcc 4.8

where error in code? or in compiler (which highly doubt)?

just i'll declare variable ('tmp') , use index in call of fscanf:

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

i'm sorry if there spelling/grammar errors; english not native language.

in loops, change c<=corecount c<corecount have declared arrays of size [corecount] when corecount 3, have elements [0], [1], [2]. having c<=corecount in loop, try access element [3] memory outside array being corrupted.


Comments

Popular posts from this blog

PHPMotion implementation - URL based videos (Hosted on separate location) -

javascript - Using Windows Media Player as video fallback for video tag -

c# - Unity IoC Lifetime per HttpRequest for UserStore -