Segmentation Fault when attempting to print value in C

三世轮回 提交于 2019-12-17 14:49:00

问题


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 <stdio.h>

int main() 
{
    int* n;
    *n = 20;

    printf("%i\n",*n);

    return 0;

}

回答1:


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);



回答2:


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;



回答3:


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


来源:https://stackoverflow.com/questions/11278085/segmentation-fault-when-attempting-to-print-value-in-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!