我非常新的C所以也许有人可以阐明为什么我收到这个程序分段错误一些轻:字符指针造成分段错误
#include <stdlib.h>
#include <stdio.h>
int main()
{
char *username = "hello";
char *other;
*other = *username;
return 0;
}
这是为什么呢赛格断层?
我非常新的C所以也许有人可以阐明为什么我收到这个程序分段错误一些轻:字符指针造成分段错误
#include <stdlib.h>
#include <stdio.h>
int main()
{
char *username = "hello";
char *other;
*other = *username;
return 0;
}
这是为什么呢赛格断层?
other
尚未初始化。它指向记忆中的某个随机点,并且你在那里粘着一个角色。
你想要么分配一些空间other
:
char *other = malloc(6); // or 1, or however much space you'll eventually need
*other = *username;
// first char at `other` is now 'h'; the rest is unknown. To make it valid string,
// add a trailing '\0'
other[1] = '\0';
,或者如果你正在尝试做一个重复的字符串:
char *other = strdup(username);
,或者如果你想使other
指向同一个地方username
:
char *other = username;
"Okay as I understand it char *username = "hello";
automatically allocates a place for the string."
它可能有助于更好地定义单词'it'(如上面的句子中所用);这是'编译器'(没有深入讨论链接器和加载器)。这意味着编译器在执行程序之前为静态字符串“hello”准备一个位置。例如,您可以'grep'可执行文件并发现可执行文件包含字符串'hello'。
随着程序被OS加载到内存中,会在程序可以动态分配内存的地方建立“堆”。
静态字符串“hello”不是堆的一部分;并没有在运行时动态分配。相反,它是在编译时静态分配的。
静态值(例如字符串“hello”)不能由'realloc()'调整大小,或由'free()'释放,因为这些函数仅适用于从“堆”分配的项目,而非静态“编译时”分配。
以下代码声明了一个静态字符串“hello”。 它还声明了一个字符指针“username”,并初始化指针指向静态字符串。
char *username = "hello";
以下代码声明了一个字符指针'other',并使其未初始化。作为'其他'是未初始化的,并且指针总是指向某处;未初始化的“其他”指针可能指向随机内存位置(实际上不存在)。
char *other;
下面的行试图一个字符(“H”)从其中username指向复制,到“其他”是指向(一个随机存储器位置,它实际上并不存在)。
*other = *username;
这就是生成'分段错误'的原因。
仅供参考,下面的语句将导致指针“用户名”和“其他”指向同一个地方,静态字符串“hello”:
char *other;
other = username;
...这是相同:
char *other = username;
如果你愿意的话,可能会导致“你好”从堆中分配(在运行时),如下所示:
char *username = strdup("hello");
如果你想在“其他”的另一个副本:
char *other = strdup("hello");
也许你想要做的'其他=用户名;',所以他们指向同一个地方?要么,要么你必须为'other'分配内存并使用'strcpy'。这取决于你想达到什么。 – AntonH
分配在哪里? –
'other'未初始化。 – BLUEPIXY