Question

Consider the following code below: When I run under mingw 64, and d->box is equal to "jp2 " then br also equals "jp2 ". i.e. it is null terminated. So strcmp succeeds and returns 0.

Under visual studio 2012, scrncpy doesn't return a null terminated string.

strcmp fails in this case. But, according to the strcmp docs:

///////////////////////////////////////////////////////////////////////

strcmp Compare two strings Compares the C string str1 to the C string str2.

This function starts comparing the first character of each string. If they are equal to each other, it continues with the following pairs until the characters differ or until a terminating null-character is reached.

/////////////////////////////////////////////////////////////////////////

So, strcmp should succeed, even though one string is null terminated and one string isn't.

Any ideas on why this is?

    char *br = (char*)malloc(5 * sizeof(char));
br = strncpy(br, (const char*)b->dbox, 4);

if(strcmp(br, "jp2\040")) {
    println(INFO, "DOSEN'T Conform to IS 15444-1. Exiting");
    return 1;
} else
    println(INFO, "Conforms to IS 15444-1");
Was it helpful?

Solution

strncpy() does not append a 0 byte on either system (i.e. doesn't terminate the string) if the source is as long or longer than the limit given (here 4). That means that the comparison fails because -- unless by chance there is a 0 in memory at br+4 -- the "string" at br is longer than 4, and thus different.

Fix, and good practice with unknown string sources: set the last byte of your buffer hard to 0.

br = strncpy(br, (const char*)b->dbox, 4);
br[4] = '\0';
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top