Are inline string arrays in C allocated on the stack?

In C, consider the following "string" 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};

Will it stringArraysimply contain a copy of each of the three pointers?

Will an array be allocated on the stack?

+5
source share
3 answers

stringArrayallocated on the stack, each of its elements is a pointer to char. To be more specific:

  • string1 the pointer is on the stack, its value is the address of the first character of a read-only string in a data segment
  • string2 the pointer is on the stack, its value is the address of the memory block allocated on the heap
  • string3is an array that takes up 4 * sizeof(char)bytes on the stack
  • stringArray - , 3 * sizeof(char *) .
+9

( (. )) ( ).

(string3 , ).

+1

Assuming your code snippet is part of the function (and it looks like this is because you are “doing some string copying”), then yes, everything except the storage for string2 (since this is malloc () ed) will be in the stack.

0
source

All Articles