Solved

Calling malloc twice or redefining array sizes?

Posted on 2004-04-16
4
749 Views
Last Modified: 2008-02-01
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
Comment
Question by:stefarg
  • 2
4 Comments
 
LVL 86

Accepted Solution

by:
jkr earned 85 total points
ID: 10846353
>>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
 
LVL 1

Author Comment

by:stefarg
ID: 10846383
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
 
LVL 44

Assisted Solution

by:Karl Heinz Kremer
Karl Heinz Kremer earned 40 total points
ID: 10846424
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
 
LVL 1

Author Comment

by:stefarg
ID: 10846531
That's great, thanks
0

Featured Post

Threat Intelligence Starter Resources

Integrating threat intelligence can be challenging, and not all companies are ready. These resources can help you build awareness and prepare for defense.

Join & Write a Comment

Often, when implementing a feature, you won't know how certain events should be handled at the point where they occur and you'd rather defer to the user of your function or class. For example, a XML parser will extract a tag from the source code, wh…
Many modern programming languages support the concept of a property -- a class member that combines characteristics of both a data member and a method.  These are sometimes called "smart fields" because you can add logic that is applied automaticall…
The viewer will learn additional member functions of the vector class. Specifically, the capacity and swap member functions will be introduced.
The viewer will learn how to clear a vector as well as how to detect empty vectors in C++.

760 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

20 Experts available now in Live!

Get 1:1 Help Now