Lifetime String Literal in C

Gast #4256947
Lesenswert?

Wie lange ist eigentlich die Lifetime von String Literalen in C?
Wenn ich z.B. schreiben
1
char* bar(...)
2
{
3
  ...
4
  ...
5
  return "Hello world";
6
}
7

8
int main(void)
9
{
10
  ...
11
  char *foo = bar(...);
12
  ...
13
}
oder
1
typedef struct
2
{
3
  ...
4
  char *blub;
5
  ...
6
}Foo;
7

8
int main(void)
9
{
10
  ...
11
  Foo bar = {..., "Hello world", ...};
12
  ...
13
}
schreibe, wie lange werden dann meine Pointer garantiert auf "Hello 
world" zeigen?

Danke
Moderator #4257025
Lesenswert?

Ja, das String-Literal existiert so lange, wie das Programm läuft:
1
  The multibyte character sequence is then used to initialize an array
2
  of static storage duration and length just sufficient to contain the
3
  sequence.

Aber Vorsicht: Für Compound-Literals innerhalb von Funktionen gilt das
nicht:
1
  If the compound literal occurs outside the body of a function, the
2
  object has static storage duration; otherwise, it has automatic
3
  storage duration associated with the enclosing block.

(Zitate aus dem C11-Standard)
Gast #4257049
Lesenswert?

Danke.

Hab ich es richtig verstanden, dass
1
  Foo bar = {..., "Hello world", ...};
ein Compound-Literal ist und ich es also nicht aus einer Funktion 
returnen dürfte?
Wenn ja, würde
1
char *hello_world = "Hello world";
2
Foo bar = {..., world , ...};
helfen?
#4257086
Lesenswert?

C-1/4 Profi schrieb:
> Hab ich es richtig verstanden, dass
>  Foo bar = {..., "Hello world", ...};
> ein Compound-Literal ist

Nein, das ist eine ganz normale Struktur-Initialisierung.

Compound literals sind neu in C99:
1
Foo bar = (struct Foo){..., "Hello world", ...};
Das ist hier sinnlos, weil sein Wert kopiert wird. Compound literals 
werden üblicherweise mit Zeigern benutzt:
1
Foo *bar = &(struct Foo){..., "Hello world", ...};

Antwort schreiben

Bitte melde dich an, um einen Beitrag zu schreiben.

oder

Mit Google-Account einloggen

Die Registrierung ist kostenlos und dauert nur eine Minute.

Jetzt registrieren