不明白为什么是段错误

时间:2015-03-23 10:29:06

标签: c arrays pointers segmentation-fault c-strings

我想很久以前我尝试过以下代码,一切顺利。 但现在,我有一个分段错误,我无法找出哪个部分提供它。

#include <stdio.h>
#include <stdlib.h>

int main() {
    char *test = NULL; // Empty string
    char *a = "programming test";
    int i = 0;

    /* While the string "a" does not encounter a space,
       I put its characters in the empty string "test" one by one. */

    while(a[i] != ' ') {
        test[i] = a[i];
        i++;
    }

    printf("%s\n", test);

    return 0;
}

这个小代码对我来说似乎是对的,我无法确定错误。

3 个答案:

答案 0 :(得分:5)

你没有在这里分配内存:

char *test = NULL; // Empty string

给它一些记忆:

char *test = malloc(sizeof(char) * 50);

循环nul终止后:

while(a[i] != ' ') {
    test[i] = a[i];
    i++;
}
test[i] = '\0';
printf("%s\n", test);

答案 1 :(得分:1)

您已经得到了问题的答案,但其他答案错过了通知您的是,您的问题的答案

  

不明白为什么会出现段错误

是由您的代码生成的 undefined behaviour

在您的代码中,您已使用test初始化NULL

char *test = NULL; // Empty string

稍后,如果没有将内存分配给test,您就会尝试取消引用内存。

test[i] = a[i];

这会产生未定义的行为。

来自C11标准文件,章节6.5.3.2地址和间接运营商,第4段,

  

[...] 如果是   为指针分配了无效值,unary *运算符的行为未定义。

及相关脚注(102)

  

unary *运算符解除引用指针的无效值是空指针,   地址不恰当地对齐指向的对象类型,以及对象后的地址   它的一生结束。

众所周知,数组下标运算符[]unary *运算符(*p === p[0]实现)的变体,规则适用于此类。

所以,基本上,你在这里取消引用NULL指针,创建未定义的行为。

请记住:&gt;&gt; 分段错误是具有未定义行为的副作用之一。


要解决此问题,您应该在取消引用之前为指针分配内存。

此外,同样值得一提的是, string 应始终以null结尾。

那就是说,你应该使用int main(void)作为功能签名。它是由标准推荐的。

答案 2 :(得分:0)

char * test=NULL;

您没有为指针test分配任何内存。您正在引用NULL 所以它导致分段错误。

所以为test分配内存。

 test=malloc(50);// memory you need.
相关问题