Skip to content

Instantly share code, notes, and snippets.

@jesselawson
Created April 23, 2019 20:13
Show Gist options
  • Save jesselawson/84797df2764595e96a8761dc37ce20cf to your computer and use it in GitHub Desktop.
Save jesselawson/84797df2764595e96a8761dc37ce20cf to your computer and use it in GitHub Desktop.
An example of how string literals persist in stack memory. This is NOT how you do dynamic strings!
#include <stdio.h>
#include <string.h>
int main(void) {
char* full_name = "Jesse Lawson";
char* ptr = full_name;
printf("newptr: %p\n", ptr);
full_name = "Jesse Happy Bubble Fun Club Lawson";
ptr = full_name;
printf("newptr: %p\n", ptr);
full_name = "But what happens when we continue to override the value?";
ptr = full_name;
printf("newptr: %p\n", ptr);
full_name = "The answer: new blocks of memory continue to be allocated during compile time";
ptr = full_name;
printf("newptr: %p\n", ptr);
full_name = "and you have address space in memory taken up by these string literals.";
ptr = full_name;
printf("newptr: %p\n", ptr);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment