Comparing addresses and storing strings

Possible duplicate:
How are string literals compiled in C?

I wrote a little code below. In this code, I think the address of the first and second line "hello" will be compared. I'm confused. At first glance, I thought that both lines would be stored in read-only memory and therefore would have a different address. But after the execution was printed "equal."

When I saw objdump, I could not see the welcome line. I understand that I did not take a variable to save them, but where "hello" will be stored.

Will it be stored on STACK ?? Or Will it be saved in the code segment?

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

if if ("hello" == "hell1"), " ". , . STACK?? ?

, - .

+5
3

"hello" . , , "", .

:

#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;
}

"", , , ( ). - , .

, , ( ), , " ":

#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;
}
+3

, , "" == "", , . :

    .file   "hello.c"
    .section    .rodata
.LC0:
    .string "\n equal "
    .text
.globl main
    .type   main, @function

, , "hello2" == "hello", .rodata, :

    .file   "hello.c"
    .section    .rodata
.LC0:
    .string "hello2"
.LC1:
    .string "hello"
+1

String literals, since your two "hello"can be implemented in memory by the compiler to read only and, moreover, it has the right to simply implement one such literal if the value matches.

Thus, the result of your comparison is determined by the implementation and may even vary for different versions of the same compiler or different optimization parameters that you give.

0
source

All Articles