The amount of new memory in C ++

When I try to do the following, I get an error message that I am 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 it legal?

+3
source share
3 answers

No. You make a general beginner mistake. You don’t remember that pointers are just variables that are passed by value unless you ask for a link or a pointer to them. Change the signature of your function tovoid func1(int *& ptr)

+9
source

Change your signature to:

void func1(int *& ptr)

You pass a pointer by value, so the outer one ptrdoes not change. So like doing

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

which is illegal because it is ptr_anot initialized.

+7
source

You passed a pointer by value. This means that the pointer this function works with is a local copy of the caller’s pointer. And therefore, the value that you assign to the function cannot be seen by the caller.

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

void func1(int* &ptr)

Or perhaps consider returning the newly allocated pointer:

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

I would prefer the latter approach.

+4
source

All Articles