Search code examples
cpointerscompound-literals

compound literals and pointers


It's safe initialize pointers using compound literals in such way and it's possible at all?:

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

void numbers(int **p)
{
        *p = (int []){1, 2, 3};
}

void chars(char **p)
{
        *p = (char[]){'a','b','c'};
}

int main()
{
    int *n;
    char *ch;

    numbers(&n);
    chars(&ch);
    printf("%d %c %c\n", n[0], ch[0], ch[1]);
}

output:

1 a b

I don't understand exactly how it's works, does it's not the same as init pointer with local variable?

also if i try to print:

printf("%s\n", ch);

It's print nothing.


Solution

  • A compound literal declared inside a function has automatic storage duration associated with its enclosing block (C 2018 6.5.2.5 5), which means its lifetime ends when execution of the block ends.

    Inside numbers, *p = (int []){1, 2, 3}; assigns the address of the compound literal to *p. When numbers returns, the compound literal ceases to exist, and the pointer is invalid. After this, the behavior of a program that uses the pointer is undefined. The program might be able to print values because the data is still in memory, or the program might print different values because memory has changed, or the program might trap because it tried to access inaccessible memory, or the entire behavior of the program may change in drastic ways because compiler optimization changed the undefined behavior into something else completely.