简体   繁体   English

使用C / Linux指针到指针的分段错误

[英]Segmentation Fault with pointer-to-pointer with C / Linux

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? 据我所知,如果有一个' Set **S ',那么*S是指向Set对象的指针,所以如果第二个代码工作正常,为什么不应该第一个? *S of the first code is equivalent to S of the second code, am I not right? *S第一个代码的S相当于第二个代码的S ,我不对吗? How can I solve the problem? 我该如何解决这个问题?

Set **S is not initized, but you dereference S in the next statement: Set ** S未启动,但您在下一个语句中取消引用S:

*S = whatever * S =无论如何

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. 除非你得到真正的,非常不幸的并且S指向你可以实际访问的内存位置,否则你试图取消引用无效指针。

You would need to allocate your pointer first: 您需要先分配指针:

Set **S;
S = (S**)calloc(sizeof(S*),1);
*S = getpar();

Or, alternatively (and preferable, I think): 或者,或者(我认为最好):

Set *S;
Set **T = &S;

S = getpar();

/* whatever else */

**S is not initialized. ** S未初始化。 Its pointing to nothing (garbage) and then you de-reference it in the next statement. 它指向什么(垃圾),然后在下一个语句中取消引用它。

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

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