Frage

I am trying to allocate memory in a function and I am not sure what I am doing wrong. I want this:

int main()
{
    int* test= 0;
    initialize(test, 10);
    int test2 = test[2];
    delete[] test;
}

void initialize(int* test, int count)
{
    test = new int[count];
    for (int i = 0; i < count; i++)
    {
        test[i] = i;
    }
}

But I receive this error: Unhandled exception at 0x770d15de in Robust Simulation.exe: 0xC0000005: Access violation reading location 0x00000008. It breaks on line: int test2 = test[2];

but this works:

int main()
{
    int* test=0;
    test = new int[10];
    for (int i = 0; i < 10; i++)
    {
        test[i] = i;
    }

    int test2 = test[2];
    delete[] test;
}

Is there a scoping problem? I thought since I pass it a pointer it would be allocated and I would be able to access it outside of the initialize function.

Thanks for your help

War es hilfreich?

Lösung

Do following changes:-

initialize(&test, 10);
....


void initialize(int** test, int count) 
{
     *test = new int[count];
     for (int i = 0; i < count; i++)
     {         (*test)[i] = i;     }
 }

C++ has another feature called references if you want as it is :-

void initialize(int*& test, int count)
{
         test = new int[count];
         for (int i = 0; i < count; i++)
         {         test[i] = i;     }
}

what you are doing is passing the test[from main](address will pass) and storing in another local pointer variable named test.This new variable has lifetime of function scope and will get soon deleted leaving garbage after the completion of function.

Another option is

int* test= initialize(test, 10);

and change initialize as

int* initialize(int* test, int count)
    {
             test = new int[count];
             for (int i = 0; i < count; i++)
             {         test[i] = i;     }
           return test;
    }

Andere Tipps

Pointers are also passed by value. You need:

void initialize(int*& test, int count)

Your version doesn't change the original pointer:

void initialize(int* test, int count)
{
    //test is a copy of the pointer because it was passed by value
    //...
}

After this, it's obvious why the delete[] fails - because the original pointer in main is never initialized.

You need to pass a reference to a pointer into your initialise function. Change the prototype to

void initialize(int* &test, int count) 

The return value of new is assigned to that copy of the pointer that gets created when passing by value. So when the function exits, that address is lost as the copy goes out of scope and so you have a memory leak. Thus your test pointer never actually points to any allocated memory and so deleting it gives you an access violation.

Passing by reference allows the test pointer to be modified by the function

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top