简体   繁体   English

在调用函数中取消引用指针时出现分段错误

[英]Segmentation fault while dereferencing the pointer in the calling function

When I run the following code, I get the segmentation error fault and I cannot rectify my mistake. 运行以下代码时,出现分段错误错误,并且无法纠正错误。

    void test(int *c)
{
    c++;
    *c = 10;
    cout<<*c<<endl;
}

int main()
{
    int a =2;
    int *b = &a;
    test(b);
    cout<<*b;
    return 0;
}

I think that b should point to value '2'. 我认为b应该指向值“ 2”。 But instead it gives an error. 但是相反,它给出了一个错误。

With c++ you are incrementing the value of the pointer and not the value of the integer. 使用c++您将增加指针的值而不是整数的值。 It will point to a new location that was not allocated by you, and it will raise the segmentation fault error. 它将指向您未分配的新位置,这将引发分段错误错误。 The new location may be used by an other program or by the system..... 新的位置可能被其他程序或系统使用.....

For what you move the pointer in the test ? 为了在test移动指针? You move it behind the memory of the variable a and reach undefined behavior. 您将其移到变量a的内存后面并达到未定义的行为。

  c
  |
+---+---+
| 2 |   |
+---+---+
      |
     ++c
void test(int *c)
{
   c++;
   *c = 10;

*c = 10 is undefined behavior since you are writing into memory that does not belong to you. *c = 10是未定义的行为,因为您正在写入不属于您的内存。

In function test , 'c' has address of 'a' say 1000. Now you increment this address say it gets to 1004 ,now this memory address is not allocated by you . 在功能测试中,“ c”的地址为“ a”,例如1000。现在您将该地址递增至1004,现在该内存地址不是由您分配的。

When you try to access memory which was not allocated by you , Segmentation fault occurs . 当您尝试访问未分配给您的内存时,会发生分段错误。

Now when you try to print *c ,it might print 10 but it is undefined behavior which can even crash the PC at times. 现在,当您尝试打印* c时,它可能会打印10,但这是未定义的行为,有时甚至会导致PC崩溃。

To get a better idea ,just think about free() when you free() the memory and then access a variable you might still get the value but it is undefined behavior ,anything can happen . 为了获得更好的主意,只要在释放内存()并访问变量时考虑一下空闲(),您可能仍然会得到该值,但这是未定义的行为,任何事情都可能发生。

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

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