1

Can somebody tell me why this code does not work? I tried to compile and run it with gcc 6.3, but the result of the printf is a kind of memory mess: "P@" instead of "something". Compiling it with gcc 5.3 on https://www.jdoodle.com/c-online-compiler, gives me the exact result ("something").

#include <stdio.h>

char *vari;

void foo(char **ts)
{
    char buffer[] = "something";
    *ts = &buffer[0];
}

int main (void)
{
    foo(&vari);
    printf("vari: %s\n", vari);
}
T.Barta
  • 53
  • 6
  • 1
    Undefined behavior, `buffer` doesn't exist any more once you leave `foo()`. –  Nov 27 '17 at 10:16
  • 1
    Duplicate link 1: why this doesn't work. Duplicate link 2: why you can't rely on it even if it "seems to work". Duplicate link 3: why it would work if you declared it as a pointer instead. – Lundin Nov 27 '17 at 10:20

3 Answers3

3

buffer[] has automatic storage duration.

Using a pointer that's set to its address in the caller to that function will result in undefined behaviour.

It would have been a different matter had you written

static const char* buffer = "something";

instead.

Bathsheba
  • 231,907
  • 34
  • 361
  • 483
2

This is undefined behavior. Accessing a automatic storage lifetime element outside it's scope can result in anything.

When the foo() function ends the memory of buffer is deallocated.

There are different ways you can solve the issue thought

  • Make the buffer of static storage duration.

  • Allocate memory and then copy the literal "somehting" to it and assign it to *ts.

user2736738
  • 30,591
  • 5
  • 42
  • 56
2

Lifetime of buffer will end once the function foo returns because it has automatic storage duration. This will make the behavior of your program undefined.
You can allocate memory dynamically which has static storage duration

void foo(char **ts)
{
    char *buffer= malloc(10);
    strcpy(buffer, "something")
    *ts = &buffer[0];
}
haccks
  • 104,019
  • 25
  • 176
  • 264