Forum: Compiler & IDEs Lifetime String Literal in C


von C-1/4 Profi (Gast)


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

von C-1/4 Profi (Gast)


Lesenswert?

> schreiben
Sry, das ist zu viel.

von Rolf M. (rmagnus)


Lesenswert?

C-1/4 Profi schrieb:
> Wie lange ist eigentlich die Lifetime von String Literalen in C?

Quasi "für immer".

C-1/4 Profi schrieb:
> wie lange werden dann meine Pointer garantiert auf "Hello
> world" zeigen?

Solange, wie sie existieren bzw. nicht mit einer anderen Adresse 
überschrieben werden.

von Yalu X. (yalu) (Moderator)


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)

von C-1/4 Profi (Gast)


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?

von C-1/4 Profi (Gast)


Lesenswert?

>Foo bar = {..., world , ...};
Sry, das muss
1
Foo bar = {..., hello_world , ...};
heißen, da ist beim Kopieren wohl ein Teil zurückgeblieben.

von Clemens L. (c_l)


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", ...};

Bitte melde dich an um einen Beitrag zu schreiben. Anmeldung ist kostenlos und dauert nur eine Minute.
Bestehender Account
Schon ein Account bei Google/GoogleMail? Keine Anmeldung erforderlich!
Mit Google-Account einloggen
Noch kein Account? Hier anmelden.