Tuesday, July 28, 2009

Can anybody explain me the output of the following c program ??

#include%26lt;stdio.h%26gt;


void main()


{


int no;


char name[15];


printf("\nEnter the number and the name\n");


scanf("%d %15c",%26amp;no,name);


printf("%d %15s",no,name);


}


in this program when i input the data as folows


1 123456789012345


the answer comes in the following form


1 123456789012345%@


i am not able to understand the occurence of the last two characters in the output..they get generated in random and may be anything..,,


can anybody explain me why this happens???

Can anybody explain me the output of the following c program ??
Hi,


I'm a Java programmer, so don't count my answer, it's just a suggestion.


I guess that you have exeeded your "name" array index limit with the 15 in the part: "%15s". If I'm not mistaken, the 15 is redundant when specifying the 's' parameter.


However, I don't know the reason why it only went 2 more places and not 15 for example.
Reply:Try changing char name[15] to char name[16]. C strings have a \0 at the end. Thus, the shortest C string you can have is actually two characters (one character and a \0). So if you have char name[15], you can only have a name that is 14 characters long, since you need one space for a \0.





scanf tacks on a \0 at the end, so if you have no space left for it, you go into undefined behavior as it will be added to out of bound memory area. Printf looks for that \0 (or a newline or space), so it also ends up going into undefined memory areas.
Reply:Because you're only allocating 15 characters for the string you read in after the int. In c, the last character in a string must have an ASCII code of zero for printf (and other functions like strcpy and strlen) to know where the string ends. When you type less than 15 characters, scanf is able to append a null character (ASCII code of zero) for you, but when you type exactly 15 characters there's no room for it.





So, printf is overrunning the end of your string (character array).





Here's a tutorial that might be helpful:


http://vergil.chemistry.gatech.edu/resou...
Reply:in a char array, the last character should always be '\0'; By stuffing all 15 characters, you are causing a buffer overrun.


The string gets printed until it finds the 1st '\0' which may well be a few characters down the line.





Read atleast one character less than the size of the array.


I suggest you read up fgets. For user input, its a good way to get the data.


http://www.phim.unibe.ch/comp_doc/c_manu...

apricot

No comments:

Post a Comment