繁体   English   中英

c中的char指针导致分段错误

[英]char pointers in c causing segmentation fault

我对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”(在以上句子中使用)可能会有所帮助; 这就是“编译器”(不必对链接器和加载器有太多的思考)。 the program is executed. 这意味着编译器执行程序为静态字符串“ hello”准备了一个位置。 例如,您可以“ grep”可执行文件并发现该可执行文件包含字符串“ hello”。

by the OS, a 'heap' is established where the program may allocate memory dynamically. 操作系统 ,会在程序可以动态分配内存的地方建立一个“堆”。

静态字符串“ hello”不属于堆; 并且在运行时未动态“分配”。 相反,它是在编译时静态“分配”的。

静态值(例如字符串“ hello”)无法通过“ realloc()”调整大小,也无法通过“ free()”释放,因为这些函数仅适用于从“堆”分配的项目,而不适用于静态“编译时” ”分配。


以下代码声明了静态字符串“ hello”。 它还声明了字符指针“用户名”,并初始化了指针以指向静态字符串。

char *username = "hello";

以下代码声明了一个字符指针“ other”,并将其保留为未初始化状态。 作为“其他”的对象尚未初始化,并且指针始终指向某处。 未初始化的“其他”指针可能指向随机内存位置(实际上不存在)。

char *other;

character ('h') from where username is pointing, to where 'other' is pointing (a random memory location which does not actually exist). 下面的行尝试将字符('h')从用户名指向的位置复制到'其他'指向的位置(实际上不存在的随机内存位置)。

*other = *username;

这就是产生“分段故障”的原因。


仅供参考,以下语句会使指针“用户名”和“其他”指向同一位置,即静态字符串“ hello”:

char *other;
other = username;

...与以下内容相同:

char *other = username;

如果愿意,可以使“ hello”从堆中分配(在运行时),如下所示:

char *username = strdup("hello");

如果您想要“其他”中的另一个副本:

char *other = strdup("hello");

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM