Why printf prints same string when function called back to back inside same statement

Viewed 47

In the below snippet, printf( ) prints same string even though the char array has been memset to 0.

#include <stdio.h>
#include <string.h>

char ip_addr[20];
char *ip_print(char *in)
{
    memset(ip_addr,0,20);
    strcpy(ip_addr,in);
    return ip_addr;
}
int main()
{
    printf("Ip addresses %s - %s",ip_print("226.0.0.1"),ip_print("10.1.1.1"));
    return 0;
}

output- Ip addresses 226.0.0.1 - 226.0.0.1

Expected output- Ip addresses 226.0.0.1 - 10.1.1.1

1 Answers

As @Pablo said above ip_print() updates a global variable and returns the (same) address twice. The order of evaluation of arguments, however, is unspecified so the result is undefined behavior (it may print either address twice).

Related