当零指针传递到函数时,分配的值不会更改
Follwing代码是自我解释的。指针P从主函数发送到函数f()。在f1()函数中,值更改为“ a”,并且在函数main()中反映了相同的值。
void f(char *p)
{
*p = 'a';
}
int main()
{
char v;
char *p = &v;
f(p);
printf("%c", *p);
// Output : a
return 0;
}
以下代码也有效...
char *f(char *p)
{
p = (char*)calloc(1, sizeof(char));
*p = 'a';
return p;
}
int main()
{
char *p = NULL;
p = f(p);
printf("%c", *p);
// Output : a
return 0;
}
但是在Follwing两个代码示例中,我试图使用Null指针实现同样的方法,但是我没有预期的结果“ A”,而是会遇到细分错误。
代码号。 1
void f(char *p)
{
*p = 'a';
}
int main()
{
char *p = NULL;
f(p);
printf("%c", *p);
// Output : Segmentation fault (core dumped)
return 0;
}
代码号。 2
char *f(char *p)
{
*p = 'a';
return p;
}
int main()
{
char *p = NULL;
p = f(p);
printf("%c", *p);
// Output : Segmentation fault (core dumped)
return 0;
}
请帮助我了解上述我遇到的“细分错误”的代码。
谢谢
The follwing code is self explanatory. The pointer p is sent to function f() from the main function. Inside the f1() function the values is changed to 'a' and the same gets reflected in function main().
void f(char *p)
{
*p = 'a';
}
int main()
{
char v;
char *p = &v;
f(p);
printf("%c", *p);
// Output : a
return 0;
}
The following code works too...
char *f(char *p)
{
p = (char*)calloc(1, sizeof(char));
*p = 'a';
return p;
}
int main()
{
char *p = NULL;
p = f(p);
printf("%c", *p);
// Output : a
return 0;
}
But in the follwing two code samples, I have tried to achieve the same with NULL pointer, but instead of expected result 'a', I am getting segmentation fault.
Code no. 1
void f(char *p)
{
*p = 'a';
}
int main()
{
char *p = NULL;
f(p);
printf("%c", *p);
// Output : Segmentation fault (core dumped)
return 0;
}
Code no. 2
char *f(char *p)
{
*p = 'a';
return p;
}
int main()
{
char *p = NULL;
p = f(p);
printf("%c", *p);
// Output : Segmentation fault (core dumped)
return 0;
}
Please kindly help me to understand the above codes where I am getting "Segmentation fault."
Thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
问题是,指针指向无效的地址(
null
)。通过调用“ calloc”,您将分配内存并存储该地址在传递的指针中(这意味着您传递到函数的值完全无关)。
访问无效的地址会导致不确定的行为。删除无效导致分割故障。
一个现实世界的例子应该更好地说明:
想象一下您走一条路。您带着一个Waypost来到过境点。通常,它会指出您“朝正确的方向”。但是现在它无处不在。紧随其后,它将您进入热水,沼泽,大黑洞或其他任何不愉快的地方。
The problem is, that the pointer points to an invalid address (
NULL
).By calling 'calloc' you are allocating memory and store that address in the passed pointer (meaning the value you pass into the function is completely irrelevant).
Accessing an invalid address leads to undefined behavior. Dereferencing NULL causes a segmentation fault.
A real world example should illustrate that better:
Imagine you walk down a path. You come to a crossing with a waypost. Usually, it would point you 'into the right direction'. But now it just points to nowhere. Following it will land you in hot water, a swamp, a big black hole or any other unpleasant place of your choosing.