Skip to content

Instantly share code, notes, and snippets.

@hawkw
Created October 12, 2023 02:16
Show Gist options
  • Save hawkw/7f4a9b20d489fd19afb4d5b44b957eb0 to your computer and use it in GitHub Desktop.
Save hawkw/7f4a9b20d489fd19afb4d5b44b957eb0 to your computer and use it in GitHub Desktop.
tries to print a string but accidentally prints its environment variables instead

a super obvious dangling pointer to locals. clang++ does warn you not to do this, but it doesn't care enough to stop you.

on my machine, with whatever version of clang i have, this does the extremely funny behavior of reading into the caller's stack frame and then into env vars. you may or may not be this lucky, it might just segfault or something. who can say!

#include <iostream>
using namespace std;
string &get_string(int i)
{
string strings[3] = {"foo", "bar", "baz"};
return strings[i];
}
int main()
{
string &s = get_string(0);
cout << s << endl;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment