Hello all, this is more of a conceptual question as I have not yet encountered any errors due to the shortness of my runtime right now. I have an array of pointers that point to a data structure and I have initialized it with 30 spots. Then I filled every spot with a value.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
struct example
{
int x
int y
} member, **pointer;
pointer = new member *[30];
//////////////////////////////////////////////////
// Here is where my question lies:
for (int i=0; i<30; i++)
{
pointer[i] = new member;
pointer[i]->x = 1;
pointer[i]->y = 1;
}
I will repeat the process above (under the row of forward slashes) many times throughout my program's execution changing the value every time, and my question is: if I continue to do this without using "delete[]" until my program terminates, will I run out of memory? Any insight would be great because I would rather not progress with my code until after I know this will not leak. Thanks!
struct example
{
int x
int y
} member, **pointer;
pointer = new member *[30];
for (int i=0; i<30; i++)
{
delete[] pointer; // Assuming I have already filled this value before
pointer[i] = new member;
pointer[i]->x = 1;
pointer[i]->y = 1;
}
struct example
{
int x
int y
} member, **pointer;
pointer = new member *[30];
for (int i=0; i<30; i++)
{
delete pointer[i];
pointer[i] = new member;
pointer[i]->x = 1;
pointer[i]->y = 1;
}
But this:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
struct example
{
int x
int y
} member, **pointer;
pointer = new example *[30];
for (int i=0; i<30; i++)
{
pointer[i] = new example;
pointer[i]->x = 1;
pointer[i]->y = 1;
}
for (int i=0; i<30; i++)
delete pointer[i];
delete []pointer;
Hello George,
Basic ans is,
-for every pointer like you have **pointer, you need to allocate memory using 'new' before you use it. [In your case you have two pointers **, so as per such's code, you need to use new two times and hence delete]
-for any object allocated using 'new' you need to 'delete' them.
-If you don't delete, there will be a memory leak.
-for class you can delete class object using destructor (having delete code for that object)