Scope of new memory in C++

2019-02-19 03:12发布

When I try to do the following I get an error saying I'm trying to read or write to protected memory.

void func1(int * ptr) {
    int *ptr_b = new int[5];
    ptr = ptr_b; 
}

void main() {
    int *ptr_a;
    func1(ptr_a);
    delete [] ptr_a;
}

Is this legal?

3条回答
手持菜刀,她持情操
2楼-- · 2019-02-19 03:19

No. You're making a common beginner mistake. You're not remembering that pointers are just variables that are passed by value unless you ask for a reference or pointer to them. Change the signature of your function to void func1(int *& ptr)

查看更多
Summer. ? 凉城
3楼-- · 2019-02-19 03:26

You passed the pointer by value. Which means that the pointer that the function works with is a local copy of the caller's pointer. And so the value you assign in the function cannot seen by the caller.

Pass it by reference instead so that the function can assign to the caller's pointer rather than assigning to a local copy.

void func1(int* &ptr)

Or, perhaps consider returning the newly allocated pointer:

int* func1()
{
    return new int[5];
}

I'd prefer the latter approach.

查看更多
冷血范
4楼-- · 2019-02-19 03:35

Change your signature to:

void func1(int *& ptr)

You're passing the pointer by value, so the outside ptr doesn't get changed. So it's like doing

int main() {  // <--- main returns int
    int *ptr_a;
    delete [] ptr_a;
}

which is illegal, since ptr_a is not initialized.

查看更多
登录 后发表回答