dynamic memory allocation with realloc

Discuss the development of new homebrew software, tools and libraries.

Moderators: cheriff, TyRaNiD

Post Reply
lagwagon666
Posts: 4
Joined: Sun Aug 20, 2006 5:34 am

dynamic memory allocation with realloc

Post by lagwagon666 »

Hello all,

I'm trying to allocate memory to dynamically resize an array of a class. As in other parts the malloc()-call works well for me, I tried using realloc(). But this doesn't seem to work, it always returns me a NULL-pointer. So, what function can I use to resize an array dynamically? Here's the code in question:

Code: Select all

geo_object **geo_objects;

geo_object* level::get_geo_object_address()
{
	geo_object_count++;
	geo_objects=(geo_object**)realloc(geo_objects,sizeof(geo_object)*_geo_object_count);
	return geo_objects[_geo_object_count-1];
}
Any Ideas? Thx for your help,
Dave-O
Aion
Posts: 40
Joined: Mon Jul 24, 2006 10:58 pm
Location: Montreal

Post by Aion »

Not sure if it's realated, but the size allocated should be :
-sizeof(geo_object*) * geo_object_count
Not
-sizeof(geo_object) * geo_object_count

Since you're allocating space of for an array of pointers.
PeterM
Posts: 125
Joined: Sat Dec 31, 2005 7:25 pm
Location: Edinburgh, UK
Contact:

Post by PeterM »

Why not use a std::vector of pointers?
http://www.sgi.com/tech/stl/Vector.html
lagwagon666
Posts: 4
Joined: Sun Aug 20, 2006 5:34 am

Post by lagwagon666 »

Aion wrote:Not sure if it's realated, but the size allocated should be :
-sizeof(geo_object*) * geo_object_count
you're right, that would probably have been the next problem I'd run into :) My problem was, that I tried to access the **geo_objects-var using array-style instead using pointer-arithmetics (geo_object[0] instead geo_object+0). However, thanks for solving my "future problem".

I also have an look at vectors.
Post Reply