Sign in to follow this  

malloc and realloc

This topic is 4666 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

I'm trying to make the data in my program dynamic. I fiddled around with new and delete for a while, but decided to go with malloc and free instead. The realloc function looked nice to me, since if I grew or shrunk an array, I wouldn't have to explicitly copy my old data over. However, realloc only seems to work once. The second time I try to realloc (the second time I have to grow the array) I get access violations. So, right now, every time I need to grow the array, I'm malloc-ing a new array, copying the old data over, and then pointint to the new array. Any ideas as to why realloc is failing the 2nd time I call it?

Share this post


Link to post
Share on other sites
A bit of code would help. Also, realloc won't always return the same memory address, so make sure you are setting the new address to the old address.
ptr = realloc(ptr,newsize);

Share this post


Link to post
Share on other sites
Quote:
Original post by Anon Mike
Actually you need something like this:

ptr2 = realloc(ptr, newsize);
if (!ptr2)
return failure;
ptr = ptr2;

realloc is a bug waiting to happen IMHO.


Sounds like someone is quoting Code Complete:)

CHeers
Chris

Share this post


Link to post
Share on other sites
I was doing just that. I don't have the code handy, but it's something along the lines of:
float* Array;
int size = 3;
...
Array = malloc(sizeof(float) * size);
...
size *= 2;
Array = realloc(Array, sizeof(float) * size);
...
size *= 2;
Array = realloc(Array, sizeof(float) * size);

On the second realloc, it would bomb.

Share this post


Link to post
Share on other sites
You know, if you have access to new and delete, then you also have access to std::vector, which will do all of this stuff for you - correctly and efficiently.

Share this post


Link to post
Share on other sites
Are you using C++? :p

There are multiple ways to create a dynamicly sized array... either buy using new/delete or one of the STL containers.

char *array = new char[20]; // declare an array of 20 characters

array[2]; // access character 2

delete [] array; // frees up memory

array = new char[100]; // now the array is a different size



OR


vector<int> a;

a.push_back(10); // Can continue indefinatly

a.erase(a.begin(), a.end()); // Clear out the vector

a.size(); // the number of elements in the vector

for(int i = 0; i < a.size(); i++)
{
cout << data.at(i); // One of many ways to access data
}



New and delete are better because they can be used on user-defined objects with constructers and malloc/free cannot. AND EVEN BETTER: NEW AND DELTE CAN BE OVERLOADED!!!! Now why would you possibly want to use malloc/free? :p

Share this post


Link to post
Share on other sites
Well, for one thing, it looks like you can't truly shrink the size of a std::vector.
http://www.codeguru.com/Cpp/Cpp/cpp_mfc/stl/article.php/c4027/
It says calling .resize does not reduce the the capacity of the vector. From the article, "resize() will never shrink capacity(). ", and I never came across another method that will cause capacity to shrink. So if I want to shrink the vector, I'd have to re-create it by hand anyways.

Share this post


Link to post
Share on other sites
I hate to break this to you but many implmentations of realloc don't either. Most are optimized for the case where you need to grow but not for the case where it shinks. In the shinking case sometimes the "removed" space is not put in the the available to alloc list.

If this behavior is that important to you I recommend that you write your own function that creates the new size, copies the data that you want from your old array, deletes the old array, and returns the new pointer.

With that said, you may be micro-optimizing. I don't know the particulars of what you're trying to do Step back and take a look at what you're doing and make certain that you're not creating extra work, potential for bugs, and/or maintainance issues without a measurable tangible benefit before you go forward on this task. My experience in over 20 years of programming in C (damn I'm getting old) is that realloc can cause real problems and usually is not worth it.

Share this post


Link to post
Share on other sites
Quote:
Original post by MauMan
With that said, you may be micro-optimizing. I don't know the particulars of what you're trying to do Step back and take a look at what you're doing and make certain that you're not creating extra work, potential for bugs, and/or maintainance issues without a measurable tangible benefit before you go forward on this task. My experience in over 20 years of programming in C (damn I'm getting old) is that realloc can cause real problems and usually is not worth it.


[cool] ++ratings

Share this post


Link to post
Share on other sites
What sort of problems can realloc create? That was pretty much my first question, anyways. I don't just want to be told, use X over Y, Y sucks. I want to know why Y sucks. The fact that realloc doesn't always shrink the size was a good point, and it's that kind of information I'm after.

Because I've had this issue with realloc, I already have my own function that creates a new array with the new size, copies the data over, deletes the old array, and returns the new pointer. I was looking for the reason that realloc wasn't working as I expected.

What I'm trying to do is pretty simple. I have data, sometimes large amounts and sometimes small amounts, that need to be in contiguous memory blocks. And I want to be able to add and remove what could be quite a large volume of data to the existing arrays. If the amount of data shrinks, I really want to free up that memory that is no longer in use, because it could be quite significant.

Yes, I'm micro-managing, but this is just a home project and if I can do something that boosts performance, I'll look into it and try it, headache or no. There's no time constraint or schedule I have to stick to, and "doing it the hard way" is a good way to learn.

Share this post


Link to post
Share on other sites
To see how to make vector shrink to fit, see this Guru of the Week:

Using Vector and Deque
Difficulty: 8 / 10

What is the difference between vector and deque? When should you use each one? And how can you properly shrink such containers when you no longer need their full capacity? These answers and more, as we consider news updates from the standards front.


The code is basically:

vector<Customer> c( 10000 );
c.reserve( 10 );//doesn't change size

vector<Customer>( c ).swap( c );//c will now have shrunk to the best size it can.



Read the article to see how it works.

Share this post


Link to post
Share on other sites

This topic is 4666 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.

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this