Jake Jake - 1 year ago 105
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


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

int *p;

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


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

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

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

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download