Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C Are string literals created on the stack?

Tags:

c

I'm a little bit confused about this expression:

char *s = "abc";

Does the string literal get created on the stack?

I know that this expression

char *s = (char *)malloc(10 * sizeof(char));

allocates memory on the heap and this expression

char s[] = "abc";

allocates memory on the stack, but I'm totally unsure what the first expression does.

like image 294
helpermethod Avatar asked Nov 28 '22 10:11

helpermethod


2 Answers

Typically, the string literal "abc" is stored in a read only part of the executable. The pointer s would be created on the stack(or placed in a register, or just optimized away) - and point to that string literal which lives "elsewhere".

like image 129
nos Avatar answered Dec 04 '22 11:12

nos


"abc"

String literals are stored in the __TEXT,__cstring (or rodata or whatever depends on the object format) section of your program, if string pooling is enabled. That means, it's neither on the stack, nor in the heap, but sticks in the read-only memory region near your code.

char *s = "abc";

This statement will be assign the memory location of the string literal "abc" to s, i.e. s points to a read-only memory region.

like image 37
kennytm Avatar answered Dec 04 '22 10:12

kennytm