简体   繁体   中英

Seg Fault while reading from a file in C

I'm simply trying to run this program with 3 command line arguments: 2 ints and 1 file name.

I've been running my program with:

a.out 1 2 devices.txt

devices.txt looks like this:

1

my main method looks like this:

int main(int argc, char* argv[]){
int MaxIterations, T, numDevices;
FILE *devices;

printf("Num arguments: %d \n", argc);
if(argc < 3 || argc > 4){
    printf("ERROR, need exactly 2 or 3 arguments!\n");
    return 1;
} else if (argc == 3){

    MaxIterations = argv[1]; // max iterations allowed
    T = argv[2]; // time interval
    devices = fopen("devices.in", "r");
} else {


    MaxIterations = argv[1];
    T = argv[1];
    devices = fopen(argv[3], "r");
    if(devices == NULL){
        fprintf(stderr, "CANT OPEN FILE: %s!\n", argv[3]);
        exit(1);
    }


}

FILE* file = fopen ("devices.txt", "r");
 int i = 0;

fscanf(devices, "%d", numDevices);
printf("Number of devices: %d \n", numDevices);

fclose(devices);
return 0;

}

What am I doing wrong that is giving me a seg fault? I've added debug printf's to figure out where the seg fault is actually triggering and it looks like its at:

fscanf(devices, "%d", numDevices);

Enable your compiler warnings:

This is not valid:

fscanf(devices, "%d", numDevices);

Here is want you want:

fscanf(devices, "%d", &numDevices);

d conversion specifier requires a pointer to a signed integer. You were passing the value of the (unintialized) object numDevices .

The problem is the fscanf function requires a pointer to the variable in which to store the value read from the file. You need something like

fscanf(devices, "%d", &numDevices);

The reason you're getting a segfault is that in your original code, the (uninitialised) value of numDevices is being used as the address to write to - and as it's very unlikely to be a valid writeable address, a segfault is usual way for your computer to say "No!" :)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM