vendredi 27 février 2015

Funny bahviour of sscanf

I have a piece of code below, it basically reads a text file data.txt and prints to the console, the content of data.txt is below the code listing;


/**************************************/



#include "stdio.h"
#define BUFFER_SIZE 93

int main(int argc, char *argv[]){

const char *datafile;
char line[BUFFER_SIZE],*string1;
int a,b,c,d,e;


FILE * File_ptr;

datafile = "data.txt";
File_ptr = fopen(datafile,"r");

if(File_ptr == NULL ){
printf("Error opening file %s\n",datafile);
}

while(fgets(line,BUFFER_SIZE,File_ptr) != 0){
puts(line);
sscanf(line, "%d %d %d %d %d %s", &a,&b,&c,&d,&e,string1);
printf("%d, %d, %d, %d, %d, %s\n",a,b,c,d,e,string1);

}

fclose(File_ptr);
}


/**************************************/


content in data.txt :



100 200 888 456 5443 file1.abc
180 670 812 496 5993 file2.abc
160 230 345 546 5123 file3.abc
23 455 342 235 214 file4.abc
233 5455 3142 2435 1214 file5.abc


What I don't understand is, If the BUFFER_SIZE is define as < 97, the output would be like this ;



100 200 888 456 5443 file1.abc

100 200 888 456 5443 (null)
180 670 812 496 5993 file2.abc

180 670 812 496 5993 (null)
160 230 345 546 5123 file3.abc

160 230 345 546 5123 (null)
23 455 342 235 214 file4.abc

23 455 342 235 214 (null)
233 5455 3142 2435 1214 file5.abc

233 5455 3142 2435 1214 (null)


If the BUFFER_SIZE is define as 97 ~ 120, the output would be ok, like this;



100 200 888 456 5443 file1.abc

100 200 888 456 5443 file1.abc
180 670 812 496 5993 file2.abc

180 670 812 496 5993 file2.abc
160 230 345 546 5123 file3.abc

160 230 345 546 5123 file3.abc
23 455 342 235 214 file4.abc

23 455 342 235 214 file4.abc
233 5455 3142 2435 1214 file5.abc

233 5455 3142 2435 1214 file5.abc




If the BUFFER_SIZE is define as >120, Segmentation Fault will be trigger at sscanf() call.


Can someone enlighten me the reason of this behaviour ?


Thanks alot !


Aucun commentaire:

Enregistrer un commentaire