Go Premium for a chance to win a PS4. Enter to Win

x
?
Solved

Calling malloc twice or redefining array sizes?

Posted on 2004-04-16
4
Medium Priority
?
819 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 255 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 120 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

Free Tool: Site Down Detector

Helpful to verify reports of your own downtime, or to double check a downed website you are trying to access.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Templates For Beginners Or How To Encourage The Compiler To Work For You Introduction This tutorial is targeted at the reader who is, perhaps, familiar with the basics of C++ but would prefer a little slower introduction to the more ad…
Article by: evilrix
Looking for a way to avoid searching through large data sets for data that doesn't exist? A Bloom Filter might be what you need. This data structure is a probabilistic filter that allows you to avoid unnecessary searches when you know the data defin…
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++.
Suggested Courses

972 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