2012-10-01 36 views
-1

可能重复:
Segmentation Fault when trying to use scanf on a structC指针,指向分割故障

我是新来的C语言编程,并有下面的代码。

char *s; 
scanf("%s",s); 
printf("This is s %s",s); 

上述代码行导致Segementation Fault。你能解释为什么吗?是否有一些文章能让我更深入地理解这些概念?

+1

我们很多年做C,但你可以尝试,也许用char * s =(char *)malloc(sizeof(char)* 30)替换'char * s;';'?这应该让's'指向一个允许30个字符的缓冲区。在你的最后一行之后,写下'free(s);',这将释放任何资源,正如@chris所指出的那样。 – npinti

+3

什么让你觉得你拥有随机未初始化的内存,只要's'碰巧指向哪里? – chris

+0

检查我刚刚链接的问题 - 您需要为要读入的字符串分配空间。 –

回答

1

您可以写入内存地址拥有该特定实体

对于如:

char s[10]; 

存储为s10字符所需的编译器储备足够的内存,你可以自由地写它。

当你说:

char *s; 

指针s只是点到未拥有或为它保留了一些随机的内存地址。写入该内存地址会导致写入其他实体拥有的内存。从技术上讲,这是未定义的行为
实际上,段错误可能发生或不发生,具体取决于写入的存储器地址是否属于某个其他实体。所以你很幸运得到了引起你注意的崩溃。无论如何,这是未定义的行为,因此应该始终避免。

您需要为指针分配内存以便能够使用任何有意义的内存。它是堆栈或堆上的内存,但它应该是拥有的,因此它们都可以写入。

+0

感谢您的帮助。 –

+0

任何技术推理,这downvote非常赞赏或者只是你的狗吠叫声太大? –

0

指针存储地址。 ,并且该地址应始终为某些保留内存的地址。

表示做完char *s之后。您需要使用malloccalloc来预留/分配一些内存。

char *s=malloc(10*sizeof(char)); 

假设char的大小为1个字节,这将分配10个字节的内存。 记住您需要free您的目的完成后,您使用免费功能分配的内存。

0

你已经创建了一个指针,但是现在它没有初始化(可能指向你没有权限访问的地方)。

char *s; 

要么声明它作为数组

char s[20]; //this number should be big enough to hold the input 

或者分配一些存储器中,然后指向它。

char *s = (char *) malloc (20*sizeof(char)); 

参见:scanf

1

用数组和指针的使用与fgets试试这个:

static void get_input() 
{ 
    /* Array of 32 btyes long - no input can be 32 characters in total */ 
#define CHAR_SIZE 32 
    char str_array[CHAR_SIZE]; 
    char *str_ptr = calloc(sizeof(char), CHAR_SIZE); 

    /* Get input from user - limit the input to 32 bytes using fgets which is safer */ 
    printf("Please enter something: "); 
    /* Clear the memory before using it */ 
    memset(str_array, 0, CHAR_SIZE); 
    fgets(str_array, CHAR_SIZE, stdin); 
    printf("The input was [ %s ]\n", str_array); 

    /* Doing the same thing with a pointer */ 
    printf("Please enter something again: "); 
    fgets(str_ptr, CHAR_SIZE, stdin); 
    printf("The input again was [ %s ]\n", str_ptr); 

    /* free memory */ 
    free(str_ptr); 
} 

希望它能帮助,

+0

感谢您的帮助。 –