c - Unexpected behaviour, Garbage prints after string -
i trying animate strings before terminating application. called attached piece of code so. keeps on printing garbage till core dumped.
here code..
int terminate_msg(int quit_flag) { char server_msg[] = "\napplication not alive"; char exit_msg[] = "\nterminating application...\n"; char *ch; int = 0; if(quit_flag == 1) { printf("%s%s", server_msg, exit_msg); while((ch = server_msg + i) != null) { printf("%c",*ch); fflush(stdout); usleep(100000); i++; } = 0; sleep(2); while((ch = exit_msg + i) != null) { printf("%c",*ch); fflush(stdout); usleep(100000); i++; } sleep(2); } return 0; }
output:
application not alive terminating application... application not alive terminating application... ���І�js�dx��lx���p�dx��x��$���p l�uz��d~�]p�up��is�@q�p�q�m�dx��І@��!p�\x��^c
though first printf()
prints correctly, don't know why garbage prints coming @ end. if there problem, garbage should come after first while loop also.
note that, when comparing *ch != '\0'
, working fine.
what wrong piece of code? i'm using gcc
in linux environment.
this condition wrong
while((ch = server_msg + i) != null)
you should try this
char ch; while ((ch = server_msg[i]) != '\0') printf("%c", ch);
the condition testing if pointer null
, isn't going happen, must test if '\0'
terminating byte reached, need dereference pointer.
since null
(void *) 0
in c, , if server_msg
valid pointer it's value > 0
, value of (void *) 0
unreachable incrementing pointer, loop never ends , program continues access pointer after it's passed valid memory points to.
of course, same problem happens here
while((ch = exit_msg + i) != null) {
Comments
Post a Comment