Jake Jake - 25 days ago 6
C++ Question

pointer segfault vs undefined behavior

Why does this code produce a segfault when running regularly, but undefined behavior instead of a segfault if I either add a command line argument or comment out calling the

cpy
function?

#include <cstdlib>
#include <iostream>
#include <cstring>
using namespace std;

int *p;

void fn() {
int n[1];
n[0]=99;
p = n;

}

void cpy(char *v) {
char x[8];
strncpy(x,v,8);
}

int main(int argc, char** argv) {
fn();
cpy(argv[1]);
cout << "p[0]:" << p[0];
}


I know
n
is a local var for the function
fn
, but is there a way I can overflow a buffer or enter something as
argv[1]
to get it to print the value that
n
held from wherever it is/was in memory?

Answer

If you don't pass an argument, then argv[1]==nullptr. Then cpy(argv[1]) is cpy(nullptr) and cpy invokes strncpy(x,nullptr,8) and segfaults.

If you comment out the cpy, then no segfault.

If you pass an argument, then cpy won't segfault. But then you get to a different problem: fn did p=n but n was declared on the stack, and so back in main at cout<<p[0], p points at the object n which no longer exists, and so the behavior is undefined.