c++ - pointer segfault vs undefined behavior -
why code produce segfault when running regularly, undefined behavior instead of segfault if either add command line argument or comment out calling 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 local var function fn, there way can overflow buffer or enter argv[1] print value n held wherever is/was in memory?
if don't pass argument, argv[1]==nullptr. cpy(argv[1]) cpy(nullptr) , cpy invokes strncpy(x,nullptr,8) , segfaults.
if comment out cpy, no segfault.
if pass argument, cpy won't segfault. different problem: fn did p=n n declared on stack, , in main @ cout<<p[0], p points @ object n no longer exists, , behavior undefined.
Comments
Post a Comment