Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Address comparison and string storage [duplicate]

Tags:

c

Possible Duplicate:
How are string literals compiled in C?

I wrote the small code below. In this code, I think the address of first and second "hello" string would be compared. I am confused in this. In first look, I thought that both the strings would be stored in Read only memory and thus would have different address. But "equal" got printed after the execution.

When I saw the objdump, I was not not able to see the string hello. I understand that I have not taken a variable to store them, but where would "hello" be stored.

Will it be stored on STACK ?? or Will it be stored on Code Segment ??

#include<stdio.h>
int main()
{
    if ("hello" == "hello")
        printf("\n equal ");
    else
        printf("\n not equal");
    return 0;
}

When I changed the if condition to if ("hello" == "hell1"), "not equal" got printed. Again, where and how are the strings getting stored. Will it be stored on STACK ?? or Will it be stored on Code Segment ??

I would really appreciate if someone here gives me en elaborate answer. Thanks

like image 779
Manik Sidana Avatar asked Oct 07 '22 20:10

Manik Sidana


1 Answers

In your particular example, the "hello" strings are not even part of the code. The compiler is smart enough to detect that the code will always and forever anon print "equal" so it stripped them out entirely.

If your code looked like this, however:

#include<stdio.h>
int main()
{
    const char *h1 = "hello";
    const char *h2 = "hello";
    if (h1 == h2)
        printf("\n equal ");
    else
        printf("\n not equal");
    return 0;
}

You would still get "equal", even though, however, the comparison will actually be done (when compiled without extra optimizations). It's an optimization - the compiler detected that you have two identical, hard-coded strings and merged them in the resulting binary.

Whereas, if your code looked like this, the compiler wouldn't be able to guess (by default) that they're the same, and you'll see the "not equal" message:

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

int main()
{
    char *h1 = malloc(sizeof(char) * 10);
    char *h2 = malloc(sizeof(char) * 10);

    strcpy(h1, "hello");
    strcpy(h2, "hello");

    if (h1 == h2)
        printf("\n equal ");
    else
        printf("\n not equal");

    free(h1);
    free(h2);

    return 0;
}
like image 54
Mahmoud Al-Qudsi Avatar answered Oct 12 '22 19:10

Mahmoud Al-Qudsi