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?
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)
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.
Or, perhaps consider returning the newly allocated pointer:
I'd prefer the latter approach.
Change your signature to:
You're passing the pointer by value, so the outside
ptr
doesn't get changed. So it's like doingwhich is illegal, since
ptr_a
is not initialized.