How to new a structure containing pointer

Dear All,
I am trying to new a structure,
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
typedef struct{
    int *nodeIndex;
    int *linkIndex;
    int c_start;
    int c_end;
} typeDMA;

// i use the following code snippet to new it and delete it:

typeDMA *gtDMA;
gtDMA = new typeDMA[6];  // new the structure itself
for(int i=0; i<6; i++)
{
    gtDMA[i].nodeIndex = new int[100];  // new node index
    gtDMA[i].linkIndex = new int[100];  // new link index
    
}

// use the sturcture to do sth

// release the sturecture
for(int i=0; i<6; i++)
{
    delete []gtDMA[i].nodeIndex;
    delete []gtDMA[i].linkIndex;    
}

delete []gtDMA;



My question is: did i use the sturecture correctly? will it cause any memory leak? How can i know whether memory is leaking?

Thanks
You did it correctly. But if you are thinking, that keeping track of this stuff is cumbersome, you are not alone. Many people thought so and that's why they invented e.g. the Standard Template Library.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
typedef struct{
    vector<int> nodeIndex;
    vector<int> linkIndex;
    int c_start;
    int c_end;
} typeDMA;

// i use the following code snippet to new it and delete it:

vector<typeDMA> gtDMA(6);
for(int i=0; i<6; i++)
{
    gtDMA[i].nodeIndex = vector<int>(100);  // new node index
    gtDMA[i].linkIndex = vector<int>(100);  // new link index
    
}

// use the sturcture to do sth

// no release necessary. Everything is destructed automatically

// if you need to manually reset things, do this:
gtDMA.clear(); // reset the vector to 0 elements and freeing all other 


For your second question: There are a couple of non-portable tools for debugging memory problems, but all are quite cumbersome to use too.

Ciao, Imi.
First of all, don't declare it like that. That's a C way and should not be used in C++.

Once you've fixed that, it a construtor.
1
2
3
4
5
6
7
8
9
struct typeDMA
{
   typeDMA() : nodeIndex(0), linkIndex(0) {}

    int *nodeIndex;
    int *linkIndex;
    int c_start;
    int c_end;
};
Last edited on
Topic archived. No new replies allowed.