Segmentation Fault when attempting to print value in C

后端 未结 3 1373
夕颜
夕颜 2020-12-07 01:47

The following C code returns a \"segmentation fault\" error. I do not understand why it does not return the value 20. What is my error?

#include 

        
3条回答
  •  無奈伤痛
    2020-12-07 02:37

    You haven't allocated space for your int, you've only declared a pointer to an int.

    The pointer is uninitialized, and so writing to that unknown space in memory is undefined behavior and causes problems. This typically causes a segfault.

    You can allocate a slot for an integer using malloc:

    n = malloc(sizeof(int));
    

    And use a corresponding call to free to free up the memory later:

    free(n);
    

    But allocating a single slot for an integer is pretty unusual, typically you would allocate the int on the stack:

    int n;
    n = 20;
    

提交回复
热议问题