Luigi Auriemma

aluigi.org (ARCHIVE-ONLY FORUM!)
It is currently 19 Jul 2012 19:10

All times are UTC [ DST ]





Forum locked This topic is locked, you cannot edit posts or make further replies.  [ 2 posts ] 
Author Message
 Post subject: [c] scanf("%10s",buff) segmentation fault
PostPosted: 02 Jan 2009 14:27 

Joined: 02 Jan 2009 12:00
Posts: 3
Hi everybody. I am newbie that is trying to test a program and this morning I found the line below in the source.

Code:
scanf("%10s",buff);


buff is an array of 10 char. Then, I used different inputs to see the behavior and I discovered that sometimes the program can crash. My question is, why? I wrote these lines to study more deeply the behavior of scanf.

Code:
[gnix@localhost array]$ cat scanf.c
#include <stdio.h>

int main()
{
        char buff[10];
        scanf("%10s",buff);

        return 0;
}


And when I execute the program I get the following results:

Code:
[gnix@localhost array]$ ./scanf
1234567890
Segmentation fault
[gnix@localhost array]$ ./scanf
1234567890
Segmentation fault
[gnix@localhost array]$ ./scanf
1234567890
[gnix@localhost array]$ ./scanf
12345678901234567890
[gnix@localhost array]$ ./scanf
12345678901234567890
Segmentation fault
[gnix@localhost array]$ ./scanf
12345678901234567890
Segmentation fault
[gnix@localhost array]$ su
Password:
[root@localhost array]# echo 0 > /proc/sys/kernel/randomize_va_space
[root@localhost array]# exit
exit
[gnix@localhost array]$ ./scanf
123456789
[gnix@localhost array]$ ./scanf
1234567890
^C
[gnix@localhost array]$ ./scanf
12345678901234567890
^C


Probably the segmentation faults are related to the ASLR. In any case, the %10s in the format parameter of the scanf function means that scanf will read only 10 characters, so why did the program crash?

I hope you understand my question.. and sorry if I did any mistake, but english is not my mother language.

gnix


Top
 Profile  
 
 
 Post subject: Re: [c] scanf("%10s",buff) segmentation fault
PostPosted: 02 Jan 2009 15:57 

Joined: 13 Aug 2007 21:44
Posts: 4068
Location: http://aluigi.org
the answer is off-by-one.
in short if you place a printf("%s\n", buff); after the scanf you will notice that your buff is 10 chars long plus the final NULL delimiter, so a total of 11 chars where the last char overwrites a saved parameter (like the original value of ESP or EBP).
the effect on the execution of the program can change due to various reasons.


Top
 Profile  
 
Display posts from previous:  Sort by  
Forum locked This topic is locked, you cannot edit posts or make further replies.  [ 2 posts ] 

All times are UTC [ DST ]


You cannot post new topics in this forum
You cannot reply to topics in this forum
You cannot edit your posts in this forum
You cannot delete your posts in this forum
You cannot post attachments in this forum

Search for: