• Advertisement

Archived

This topic is now archived and is closed to further replies.

memory leak question

This topic is 5157 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

Hi, I have seen in many programs having code on the following lines :-
vector <int> v;

v.push_back(...);
v.push_back(...);
v.push_back(...);
v.push_back(...);
v.push_back(...);
v.push_back(...);
...
...
v.push_back(...);

and then 
//int *v = &v[0]

int *v1 = &v[0];

and later for freeing all resources
v1 = NULL;
My question is this a potential memory leak ? Is doing this a wise idea ? Is there a better way when the amount of data to be added is not known ? EDIT : I made a small mistake in the code. I have modified it to make my question clearer. Thank you [edited by - CRACK123 on January 14, 2004 2:16:44 PM]

Share this post


Link to post
Share on other sites
Advertisement
The code you showed would not free any resources. Just assigning NULL to a pointer doesn''t deallocate anything. To clear a vector, use the clear() method.

Share this post


Link to post
Share on other sites
In fact, you don''t need to call clear() at all in this case, since the vector v will clean up after itself when it goes out of scope. The only reason you see people setting variables to NULL like you wrote is because once the vector does go out of scope (or clear() is called), the pointer is pointing to a location in memory that isn''t valid, so setting the pointer to NULL clarifies that the pointer isn''t valid any longer.

In your code, at worst, an access violation might occur if someone tried to access whatever data v1 pointed to, after the vector was cleared (manually or automatically). No memory leak would ever occur, however.

Share this post


Link to post
Share on other sites

  • Advertisement