C++ SegFault when dereferencing a pointer for cout

后端 未结 5 1543
渐次进展
渐次进展 2020-12-06 18:37

I\'m new to C++ and just trying to get a hang of it. It generally seems not too bad, but I stumbled upon this weird/pathological segfaulting behavior:

int ma         


        
5条回答
  •  自闭症患者
    2020-12-06 18:45

    int* b points to an unknown memory address because it wasn't initialized. If you initialized it to whatever null pointer value exists for your compiler (0 until C++11, nullptr in C++11 and newer), you'd most certainly get a segfault earlier. The problem lies in the fact that you allocated space for the pointer but not the data it points to. If you instead did this:

    int c = 27;
    int* b = &c;
    
    cout << "c points to " << c << endl;
    printf ("b points to %d\n", *b);
    cout << "b points to " << (*b) << endl;
    

    Things would work because int* b refers to a memory location that is accessible by your program (since the memory is actually a part of your program).

    If you leave a pointer uninitialized or assign a null value to it, you can't use it until it points to a memory address that you KNOW you can access. For example, using dynamic allocation with the new operator will reserve memory for the data for you:

    int* b = new int();
    *b = 27;
    int c = *b;
    
    //output
    
    delete b;
    

提交回复
热议问题