1

For instance, I have 10 of these calls in a function,

snprintf(dest, sizeof(dest), "%s", "Hello World");

Then, would "Hello World" be stored on the stack a total of ten times (resulting in 11+(1) bytes * 10 = 110 bytes)?

Please let me hear your thoughts. Thanks.

  • "Hello world" is a string literal, so only a pointer to it will be passed. And yes, the stack is freed when the function is returning. So.. what's your concern? – Eugene Sh. Mar 19 '19 at 21:16
  • 1
    No, the string literal will not be on the stack. See [C99 p6.4.5](http://port70.net/~nsz/c/c99/n1256.html#6.4.5) – pmg Mar 19 '19 at 21:24
  • It's possibly a compiler option whether string literals are shared or duplicated. This is a good reason for read-only string literals. – Weather Vane Mar 19 '19 at 21:27
  • If you want to save about 100 bytes memory (where it's duplicated) you can assign a pointer `char *hw = "Hello World";` and pass that pointer to `snprintf`. – Weather Vane Mar 19 '19 at 21:35
  • @WeatherVane: better to use `const char hw[] = "Hello World";` since that saves you an extra pointer's worth of memory. (Your code has a pointer and a string; the array has just a string — the array address is a constant.) – Jonathan Leffler Mar 19 '19 at 22:04
  • @JonathanLeffler ... but at the expense of a duplicated string, which has to be copied into the array at runtime. You have two arrays. – Weather Vane Mar 19 '19 at 22:38
  • @WeatherVane — well, it'd be a `static` array, and possibly at file scope. It wouldn't be an automatic array. – Jonathan Leffler Mar 19 '19 at 22:46
  • @JonathanLeffler I had assumed it would be automatic. – Weather Vane Mar 19 '19 at 22:53
  • @WeatherVane — I noticed, and that was careless of me not to add `static` as it left it open for interpretation. If the data is constant, there's no reason not to make it `static` — to save copying as you diagnosed. – Jonathan Leffler Mar 19 '19 at 22:54

1 Answers1

4

The string literal "Hello World" has "static storage duration". Practically this means it is not on the "stack". The Standard doesn't specify whether identical string literals are "collapsed" into one instance or not.

From C11 6.4.5: String Literals

  1. ... The multibyte character sequence is then used to initialize an array of static storage duration and length just sufficient to contain the sequence. ...
    7 It is unspecified whether these arrays are distinct provided their elements have the appropriate values. If the program attempts to modify such an array, the behavior is undefined

"Stack" is in quotes above, because the standard doesn't ever mention "Stack" or "Heap" or "ROM". There's only "automatic" or "allocated" or "static" storage duration. Most compilers do have a one-to-one mapping of the concepts.

AShelly
  • 34,686
  • 15
  • 91
  • 152