tags:

views:

43

answers:

2

Hi
I wrote a C code that a portion of it is:

...
    P *head=NULL,*cur=NULL;
    char Name,tmp[255];
    int AT,ET;
    FILE *iF;

    if((iF=fopen(fileName,"r"))>0){
        fgets(tmp,255,iF);
        sscanf(tmp,"Interval:%d\n",&quantum);
        fgets(tmp,255,iF); //waste

        while(!feof(iF) &&  fgets(tmp,255,iF)){
            sscanf(tmp,"%20c %20d %20d",&Name,&AT,&ET);
...

After execution of last sscanf (last line) values of *head & *cur change (they are not NULL anymore!!)
What's the problem?

Thanks

+4  A: 

What you have is a classic buffer overflow. You are reading 20 characters into the one byte Name, and the extra characters are being written over the space occupied by head and cur and beyond that, probably trampling the return information that is stored on the stack. If you printed the values of head and cur in hex, you'd probably find that the values corresponded to the data entered in Name. For example, if you typed 'AAAAAAAAAAAAAAAAAAAA' into Name, you'd likely find that both head and cur contained 0x41414141 if you are working on a 32-bit machine.

You need to make Name into an array - and you can drop the '&' when you pass it to sscanf(). It might be that you expect:

char Name, tmp[255];

to declare both Name and tmp as arrays of 255 characters; that is not how C works, though. The declaration is equivalent to:

char Name;
char tmp[255];
Jonathan Leffler
Thanks you very much.
Snigger
I'm running out of reasons to up-vote really nice answers that you provide. So +1, Glad you're here.
Tim Post
A: 

Check documentation of fopen(). And c-faq

Nyan