Skip to content

Instantly share code, notes, and snippets.

@jvns
Created October 1, 2013 01:39
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jvns/6772832 to your computer and use it in GitHub Desktop.
Save jvns/6772832 to your computer and use it in GitHub Desktop.
Do a weird thing with the stack in C
#include <stdio.h>
void set_strings(char*** strings) {
char* strs[] = {"banana"};
*strings = strs;
}
int main() {
char** strings;
set_strings(&strings);
printf("First print: '%s'\n", strings[0]);
char* s = "abc";
printf("Second print: '%s'\n", strings[0]);
}
@nitrix
Copy link

nitrix commented Dec 19, 2013

Reading your blog post, I had to leave a comment and try to help you there. There is no such thing as stack or heap in C. Instead, there is 4 storage duration: automatic, allocated, static and thread. This code has undefined behavior and is bound to fail on most platforms in most scenarios. You should not be surprised.

Another detail, the fact you have a 3-star pointer line #3 tells me you have a biased understanding of pointers.
You should get a good book like K&R and work through the exercises. Keep it up (:

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment