1

I am trying to compare 2 strings using the below code:

char a[100] = "\0";
char* b[10];
for (int i = 0; i < 10; i++)
    b[i] = "";
b[0] = "xy";
a[0] = 'x';
a[1] = 'y';
int c = strcmp(a, b[0]);

I think both a and b[0] contain the string "xy", so I expect int c equal 0. However the result stored in int c is -858993460. Why would that happen? What should I do in order to avoid this fault? Thank you very much.

Update: I found that there is some error on my computer...

char a[3] = { NULL };
char d[3] = { NULL };
a[0] = 'x';
a[1] = 'y';
a[2] = '\0';

d[0] = 'x';
d[1] = 'y';
d[2] = '\0';
int c = strcmp(a, d);

Even using this code, I got int c to be a negative value. I have no idea why that happened.

Brian Tsui
  • 21
  • 2

1 Answers1

2

It is undefined behaviour because a is not null terminated. All string in C have to be null terminated to be used in strcmp. What strcmp does is looping over the two strings until either one of the two is NULL terminated (see Implementation of strcmp to get an idea of how it works). You can see that if '\0' is not present anywhere you got a problem there.

Read Why do strings in C need to be null terminated? for more info:

Davide Spataro
  • 7,319
  • 1
  • 24
  • 36