Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Are inline string arrays in C allocated on the stack?

In C, consider the following "inline" string arrays:

char *string1 = "I'm a literal!";
char *string2 = malloc((strlen(string1) + 1) * sizeof(char));
//Do some string copying
...
char string3[] = {'a','b','c','\0'};
char *stringArray[] = {string1, string2, string3};

Would stringArray simply contain a copy of each of three pointers?

Would the array be allocated on the stack?

like image 679
Joel Avatar asked Nov 19 '10 19:11

Joel


People also ask

Where are C strings stored?

When strings are declared as character arrays, they are stored like other types of arrays in C. For example, if str[] is an auto variable then the string is stored in stack segment, if it's a global or static variable then stored in data segment, etc.

Are rust arrays stored on the stack?

Rust arrays are value types: they are allocated on the stack like other values and an array object is a sequence of values, not a pointer to those values (as in C). So from our examples above, let a = [1_i32, 2, 3, 4]; will allocate 16 bytes on the stack and executing let b = a; will copy 16 bytes.

How are string represented in memory in C?

A string constant in C is represented by a sequence of characters within double quotes. Standard C character escape sequences like \n (newline), \r (carriage return), \a (bell), \0x17 (character with hexadecimal code 0x17), \\ (backslash), and \" (double quote) can all be used inside string constants.


1 Answers

The stringArray is allocated on the stack, each of its element is a pointer to a char. To be more specific :

  • string1 pointer is on the stack, its value is the address of the first character of a read-only string in the data segment
  • string2 pointer is on the stack, its value is the address of a memory block allocated on the heap
  • string3 is an array which occupies 4 * sizeof(char) bytes on the stack
  • stringArray is an array which occupies 3 * sizeof(char *) bytes on the stack.
like image 195
icecrime Avatar answered Sep 21 '22 20:09

icecrime