Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

String comparision without strcmp()

strcmp compares the string content hence it's preferred over if (str1 == str2) which compares the bases address of the strings.

If so, why would the if condition get satisfied in the below C code:

    char *p2="sample1";
    char* str[2]={"sample1","sample2"};


    if(p2==str[0])
    {
            printf("if condition satisfied\n");
    }

GDB:

(gdb) p p2
$1 = 0x4005f8 "sample1"
(gdb) p str[0]
$2 = 0x4005f8 "sample1"
(gdb) p &p2
$3 = (char **) 0x7fffffffdb38
(gdb) p &str[0]
$4 = (char **) 0x7fffffffdb20
(gdb) p *p2
$5 = 115 's'

What exactly is 0x4005f8 and how do I print it?

like image 361
anurag86 Avatar asked Jan 01 '23 22:01

anurag86


2 Answers

Whether same string literals will be allocated different storage, or the same storage will be used to indicate all usage of a string literal, is unspecified.

In you case, the string literal "Sample1" has only one copy, and the same address is assigned to both p2 and str[0]. However, this is not guaranteed by the standard.

Quoting C11, chapter 6.4.5

It is unspecified whether these arrays are distinct provided their elements have the appropriate values. [...]

like image 78
Sourav Ghosh Avatar answered Jan 13 '23 05:01

Sourav Ghosh


C language allows for static strings to be unique on program. This means, the compiler is allowed to decide if it optimizes the allocation (once instead of twince) for the static string "sample1".

You initialize p to point to the area where it is stocked and str[0] is also a pointer to the same static string. Hence, if they are equal or not is implementation dependent and the result of checking for equality is undefined.

Quote from 6.4.5p6, String literals

It is unspecified whether these arrays are distinct provided their elements have the appropriate values.

like image 29
alinsoar Avatar answered Jan 13 '23 04:01

alinsoar