Segmentation Fault when attempting to print value in C

后端 未结 3 1314
夕颜
夕颜 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:32

    You haven't allocated memory to n, so

    *n = 20;
    

    attempts to write unspecified memory.

    Try

    #include <stdlib.h>
    
    int *n = malloc(sizeof *n);
    /* use n */
    free(n);
    
    0 讨论(0)
  • 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;
    
    0 讨论(0)
  • 2020-12-07 02:37

    You are trying to write 20 in garbage value. You must allocate space for it by using one of *alloc() functions or creating an int on stack and getting the andress of it(as Richard J. Ross III mentioned on comments).

    dynamic allocation:

    int n*; 
    n = malloc(sizeof(int));  /* allocate space for an int */
    if(n != NULL) {
     /* do something.. */ 
     free(n); /* free 'n' */
    } else {
      /*No space available. */
    }
    

    or on the stack:

    int int_on_stack;
    int *n = &int_on_stack;
    *n = 20;
    printf("%i\n", *n); // 20
    
    0 讨论(0)
提交回复
热议问题