C / Linux 中指针到指针的分段错误
在下面的代码中,我遇到了分段错误:
Set *getpar() {...}
char function(...)
{
Set **S;
*S = getpar(); /* Segmentation Fault */
...
}
但奇怪的是,只需进行很少的更改,就不会出现分段错误:
Set *getpar() {...}
...
char function(...)
{
Set *S; // One less '*'
S = getpar(); // One less '*'
...
}
据我所知,如果有“Set **S
”,则 *S
是一个指向 Set
对象的指针,所以如果第二个代码可以正常工作,为什么第一个代码不能呢? 第一个代码的 *S
相当于第二个代码的 S
,我说得对吗? 我该如何解决这个问题?
In the following code I get a segmentation fault:
Set *getpar() {...}
char function(...)
{
Set **S;
*S = getpar(); /* Segmentation Fault */
...
}
But the bizarre thing is that with few changes there is no segmentation fault:
Set *getpar() {...}
...
char function(...)
{
Set *S; // One less '*'
S = getpar(); // One less '*'
...
}
As I know, if there is a 'Set **S
' then *S
is a pointer to a Set
object, so if the second code works fine, why shouldn't the first? *S
of the first code is equivalent to S
of the second code, am I not right? How can I solve the problem?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
Set **S 未初始化,但您在下一条语句中取消引用 S:
*S =whatever
除非您真的非常不幸并且 S 指向您实际可以访问的内存位置,否则您将尝试取消引用无效指针。
您需要首先分配指针:
或者,或者(我认为更好):
Set **S is not initized, but you dereference S in the next statement:
*S = whatever
Unless you get really, really unlucky and S is pointing to a memory location you can actually access, you're trying to dereference an invalid pointer.
You would need to allocate your pointer first:
Or, alternatively (and preferable, I think):
**S 未初始化。 它没有指向任何内容(垃圾),然后您在下一个语句中取消引用它。
**S is not initialized. Its pointing to nothing (garbage) and then you de-reference it in the next statement.