Unexpected behavior, garbage prints after line

I was just trying to animate some lines before the application exits. For this, I named the attached code. but it keeps printing garbage until the kernel is dumped.

This is the code ..

int terminate_msg(int quit_flag)
{
    char server_msg[] = "\nApplication Not Alive";
    char exit_msg[] = "\nTerminating Application...\n";
    char *ch;
    int i = 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++;
        }
        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

      

Although the former printf()

prints correctly, I don't know why garbage prints appear at the end. If there is any problem, garbage should appear after the first while loop.

Please note that *ch != '\0'

everything works fine in comparison .

What's wrong with this code? I am using gcc

in linux environment.

+3


source to share


2 answers


This condition is wrong

while((ch = server_msg + i) != NULL)

      

you should try this

char ch;

while ((ch = server_msg[i]) != '\0')
    printf("%c", ch);

      



the condition is checked if a pointer NULL

, which most likely will not happen, what you should check is if the trailing byte has '\0'

been reached, for that you need to dereference the pointer.

Since NULL

basically (void *) 0

in c, and if server_msg

is a valid pointer then that value is definitely, > 0

then the value is (void *) 0

not available just by incrementing the pointer, so the loop never ends and your program continues to access the pointer after it has passed valid memory to which it points.

Of course the same problem is happening here

while((ch = exit_msg + i) != NULL) {

      

+5


source


In your case, inside a loop with exponent i

( i++;

)

 server_msg + i

      

points to the next memory location server_msg

on each iteration. The problem here is that there is no guarantee that the closest next address (after the end of the line) will be NULL

. It may well be a valid region of memory (most likely to be) to pass the test NULL

.



So your loop will not break (as you expected), it will continue execution and (try) to access the unbound memory region, which in turn calls undefined . So the output and behavior is undefined as well.

Rather, you must answer the value *ch

as \0

for evaluating line completion.

+3


source







All Articles