为什么在调用strcmp或strcpy时仍然出现分段错误? [英] Why do I keep getting a segmentation fault when calling strcmp or strcpy?
本文介绍了为什么在调用strcmp或strcpy时仍然出现分段错误?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
亲爱的所有
我是Linux的新手,现在我遇到了以下简单代码的问题.
Hi, dear all
I''m new to Linux and now I have got a problem with the following simple code.
void main()
{
char* Pin;
char* temp;
scanf("%9[^\n]", temp);
//fgets(temp,1024,stdin);
//I also tried fgets. No luck.
strcpy(Pin,temp);
//Here comes the segfault. I tried other string manipulation functions like strcmp and
//strlen. While strcmp and all other functions which change the contents of the string
//give me segfaults, strlen returns 4 no matter how long the input is.
}
有人知道我在做什么错吗?
谢谢
作业系统:Ubuntu 11.04
编译器:gcc(Ubuntu/Linaro 4.5.2-8ubuntu4)4.5.2
Does anybody know what I''m doing wrong?
Thanks
OS: Ubuntu 11.04
Compiler: gcc (Ubuntu/Linaro 4.5.2-8ubuntu4) 4.5.2
推荐答案
当程序尝试写入内存的一部分时,会发生分段错误内核不允许访问.
您的2个char *指针未初始化,因此可以指向任何地方.那么当您尝试写入这些指针时,您将遇到分段错误.
strlen不会失败的原因是因为它只是一次读取,有时环境会让您读取无法写入的内存区域.
我知道链接只是Wikipeadia,但它会更详细地说明.
http://en.wikipedia.org/wiki/Segmentation_fault [
a segmentation fault occurs when the program tries to write to a part of memory that the kernel does not allow access to.
Your 2 char* pointers are not initialized and so could point to anywhere. then when you try to write to these pointer you will get a segmentation fault.
The reason strlen does not fail is because it''s only a read and sometimes environments will let you read memory areas that you cannot write to.
I know the link is only Wikipeadia but it explains in more detail.
http://en.wikipedia.org/wiki/Segmentation_fault[^]
To fix this make some buffers and point you pointers into them making sure not to overrun the buffers.
@SafarTimura
非常感谢您的回答.
//我已经像下面这样更改它,现在它可以正常运行:)
void main()
{
//char * Pin = new char [10];
//char * temp = new char [10];
//上面的两行在纯C语言中正确吗?
char Pin [10];
char temp [10];
scanf(%9 [^ \ n]",temp);
int结果;
result = strcpy(Pin,temp);
printf(%d",result);
}
@SafarTimura
Thank you very much for the answer.
//I''ve changed it like below and now it runs fine:)
void main()
{
//char* Pin=new char[10];
//char* temp=new char[10];
//Are the 2 lines above correct in plain C?
char Pin[10];
char temp[10];
scanf("%9[^\n]", temp);
int result;
result=strcpy(Pin,temp);
printf("%d",result);
}
这篇关于为什么在调用strcmp或strcpy时仍然出现分段错误?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文