c - Weird behavior of printf() calls after usage of itoa() function -
i brushing c skills.i tried following code learning usage of itoa()
function:
#include<stdio.h> #include<stdlib.h> void main(){ int x = 9; char str[] = "ankush"; char c[] = ""; printf("%s printed on line %d\n",str,__line__); itoa(x,c,10); printf(c); printf("\n %s \n",str); //this statement printing nothing printf("the current line %d",__line__); }
and got following output:
ankush printed on line 10 9 //here nothing printed current line 14
the thing if comment statement itoa(x,c,10);
code above mentioned statement printed , got following output:
ankush printed on 10 line ankush //so got printed current line 14
is behavior of itoa()
or doing wrong. regards.
as folks pointed out in comments, size of array represented variable c
1. since c requires strings have null terminator, can store string of length 0 in c
. however, when call itoa
, has no idea buffer you're handing 1 character long, happily keep writing out digits memory after c
(which memory contains str
).
to fix this, declare c
of size large enough handle string plan put it, plus 1 null terminator. largest value 32-bit int
can hold 10 digits long, can use char c[11]
.
to further explain memory overwriting situation above, let's consider c
, str
allocated in contiguous regions on stack (since local variables). c
might occupy memory address 1000 (because 0 character string plus null terminator), , str
occupy memory address 1001 through 1008 (because has 6 characters, plus null terminator). when try write string "9" c
, digit 9 put memory address 1000 , null terminator put in memory address 1001. since 1001 first address of str
, str
represents zero-length string (null terminator before other characters). that's why getting blank.
Comments
Post a Comment