为什么这是分段错误? [英] Why this is segmentation fault ?

查看:82
本文介绍了为什么这是分段错误?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

int main()
{
    char *str;
    strcpy(str,"Hello");
    printf("%s",str);
    return 0;
}





我的尝试:



我在调试器的帮助下尝试过,它在Codeblocks IDE中显示Segmentation fault。

程序收到信号SIGSEGV,Segmentation fault。



What I have tried:

I tried with the help of debugger, it shows Segmentation fault in Codeblocks IDE.
Program received signal SIGSEGV, Segmentation fault.

推荐答案

这是因为 str 只是一个指向字符串的单元化指针。没有分配内存,可以存储输入字符串的内容,指针本身可以指向任何地方。



所以你必须分配一些内存并将其分配给指针:

This is because str is just an unitialised pointer to a string. There is no memory allocated where the content of the entered string can be stored and the pointer itself can point to anywhere.

So you must allocate some memory and assign that to the pointer:
// It is always a good idea to initialise variables
char *str = NULL;
char *heapMemory = NULL;
char stackMemory[128];

str = stackMemory;
strcpy(str,"Hello stack");
printf("%s",str);

heapMemory = (char*)malloc(128);
str = heapMemory;
strcpy(str,"Hello heap");
printf("%s",str);
// Heap memory should be freed when not used anymore
free(heapMemory);


简单:

Simple:
char * str;



str是一个char * - 指向一个字符的指针。但是在尝试复制到内存之前,你没有为变量赋值:


str is a char * - a pointer to a character. But you don't assign anything to the variable before you try to copy into the memory:

strcpy(str,"Hello");

这意味着复制操作会进入无内存区域,并且会出错。

分配一个内存区域(也许是malloc)它应该开始工作。



我讨厌标记![/编辑]

Which means that the copy operation goes to a nonexistant area of memory, and you get an error.
Assign an area of memory (with malloc perhaps) and it should start to work.

[edit]I HATE MARKDOWN![/edit]


引用:

为什么这是分段错误?

由你的程序做错了。

C语言不受管理,你必须手动管理内存,而你却无法在你的程序中执行。

By your program is done wrong.
The C language is not managed, you have to manually manage memory, and you fail to do it in your program.

strcpy(str,"Hello");



将Hello复制到您不拥有的地方,这就是段故障的原因。


您需要正确学习C语言并按照tutos。知道语法是不够的,还有很多要知道的。


Copies "Hello" to a place you don't own, that is the reason of the segment fault.

You need to learn properly the C language and follow tutos. Knowing the syntax is not enough, there is much more to know.


这篇关于为什么这是分段错误?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆