Want to protect your cyber security and still get fast solutions? Ask a secure question today.Go Premium

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 824
  • Last Modified:

Calling malloc twice or redefining array sizes?

Hey all,
I'm just curios about the consequences of calling malloc twice or assigning an array to a new size.
lets say we have

char* a = new char[10];
....
a = new char[20];

or

char* a = (char*) malloc(10);
.....
a = (char*) malloc(20);

If we do the above is it necessary to call delete or free etc before the second assignment to release the memory of (char) length 10 or is this released by default?  I'm a bit confused about this whole memory management thing.
Thanks,
Stef
0
stefarg
Asked:
stefarg
  • 2
2 Solutions
 
jkrCommented:
>>If we do the above is it necessary to call delete or free etc before the second assignment

Definitely. Otherwise, you'd create a memory leak.

>> is this released by default?

No. You are responsible for freeing memory when you no longer need it.
0
 
stefargAuthor Commented:
Ok, so how do I clear this up, can I do the following:

char* a = new char[10];
....
delete [] a;

a = new char[20];

Is that correct and free of memory leaks?
Thanks for your response,
Stef
0
 
Karl Heinz KremerCommented:
Yes, this is the right way to do it. It's important that you use the "[]" form of delete if you allocated an array with new.
0
 
stefargAuthor Commented:
That's great, thanks
0

Featured Post

Free Tool: Path Explorer

An intuitive utility to help find the CSS path to UI elements on a webpage. These paths are used frequently in a variety of front-end development and QA automation tasks.

One of a set of tools we're offering as a way of saying thank you for being a part of the community.

  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now