1

While reading about the "read only" string and came across the below snippet.

#include<stdio.h>
main()
{
    char *foo = "some string";
    char *bar = "some string";
    printf("%d %d\n",foo,bar);
}

What i understood is foo and bar both will print the same address, but I am not able to understand what actually happening in background. i.e. When the string is same it will return same address but when I modify the string addresses are different.

Yu Hao
  • 119,891
  • 44
  • 235
  • 294
zer0Id0l
  • 1,374
  • 4
  • 22
  • 36

2 Answers2

7

enter image description here

foo and bar both will print the same address

Actually, according to the standard, they are not required to have the same address, it's unspecified. But in practice, most compiler will make identical string literals holding the same address.

You can't modify a string literal, I think you mean you use different string literals, in that case, it's obvious that the string will hold different addresses.

C11 6.4.5 String literals

It is unspecified whether these arrays are distinct provided their elements have the appropriate values. If the program attempts to modify such an array, the behavior is undefined.

enter image description here

Community
  • 1
  • 1
Yu Hao
  • 119,891
  • 44
  • 235
  • 294
  • 1
    Thanks Yu. This is one nice graphical explanation. Can you please let me know which tool/app did you used for this ? :) – zer0Id0l Nov 11 '13 at 06:44
1

Build the code with

gcc yourcode.c -S -o yourcode.S

    .file   "main.c"
    .section    .rodata
.LC0:
    .string "some string"
.LC1:
    .string "%d %d\n"
    .text
    .globl  main
    .type   main, @function
main:
.LFB0:
    .cfi_startproc
    pushq   %rbp
    .cfi_def_cfa_offset 16
    .cfi_offset 6, -16
    movq    %rsp, %rbp
    .cfi_def_cfa_register 6
    subq    $16, %rsp
    movq    $.LC0, -16(%rbp)
    movq    $.LC0, -8(%rbp)
    movl    $.LC1, %eax
    movq    -8(%rbp), %rdx
    movq    -16(%rbp), %rcx
    movq    %rcx, %rsi
    movq    %rax, %rdi
    movl    $0, %eax
    call    printf
    leave
    .cfi_def_cfa 7, 8
    ret
    .cfi_endproc
.LFE0:
    .size   main, .-main
    .ident  "GCC: (Ubuntu/Linaro 4.6.3-10ubuntu1) 4.6.3 20120918 (prerelease)"
    .section    .note.GNU-stack,"",@progbits

[char * foo] and [char *bar] are pointed to the same address. In this case "some string" is not permitted to modify. That will cause a runtime exception.

Daniel Chen
  • 103
  • 7