堆内存范围 [英] Scope of Heap Memory

查看:87
本文介绍了堆内存范围的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

据我所知,堆应该是全球性的,不是吗?因此,我们应该能够在函数中需要的任何地方访问堆内存.那为什么下面的代码出现段错误(Segmentation Fault)?

As far as I know Heaps are supposed to be global in nature, aren't they? So we should be able to access the heap memory anywhere we want in our functions. Then why does the following code segfault (Segmentation Fault)?

#include <stdio.h>
using namespace std;

void A(int* x)
{
  x = new int[10];
  for(int i = 0; i< 10; i++)
  {
    x[i] = i;
  }
}

void B(int *x)
{
  printf("%d", x[8]);
}

int main()
{
  int* a = NULL;
  A(a);
  B(a);
  return 0;
}

推荐答案

发生分段错误是因为指针a通过值传递,因此在A()中所做的更改对调用者不可见,从而导致在B()中取消引用了NULL指针.要更正,请将指针通过引用传递给A():

A segmentation fault occurs because the pointer a is being passed by value so the changes made within A() are not visible to the caller, resulting in a NULL pointer being dereferenced within B(). To correct, pass the pointer by reference to A():

void A(int*& x)

这篇关于堆内存范围的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆