Memory allocation

Started by
4 comments, last by RajanSky 21 years, 10 months ago
Hi, I''ve been running into this same problem lately and for years I''ve just been working around it without really figuring out a good way to deal with it... The problem is how to write a function which loads an array of something.. For example, I''m writing a function which loads a bunch of vertices into an array... So of course, I guess I have to make the user pass the array to me from which I will create the vertices, because if you try to dynamically create the array from within the function, that causes a memory leak (since the client of the function doesn''t know to delete this memory). But, on the other hand, if I have the client pass in a buffer to store the vertices in, that doesn''t make sense either because the client won''t know how big to make the buffer since that depends on the file being loaded! So far, in these cases my approach has just been to return a pointer from the function, and assume the user will delete it later, like this: char *img = load_bitmap("blah.bmp"); ... delete [] img; This is okay I guess, but does anyone know of a more elegant way to handle this? If you would, I''d really appreciate any tips. Thanks a lot! Rajan
Advertisement
use a std::vector and push back elements as they are loaded, or you could always do it the hard way and allocate and reallocate an array as it grows
Thanks for the idea of using a vector. But if I have a vector object, do you know how to get a pointer to the actual data in memory?

In this case, I''m trying to load an SMF file and then pass in a pointer to the glVertexPointer() function so that OpenGL can render a vertex array. But I can''t figure out how to access the actual pointer, using a vector.
One way of doing it would be to pass the function a pointer to a pointer, rather than a pointer. Like so:

  void load_bmp (const char* filename, char** array, int* num) {    // open the file and all that    // figure out the size the array should be (here: size)    *array = new char[size];    *num = size;    // Fill *array with the data}// It would typically be used like so:char* img;int size;load_bmp ("blah.bmp", &img, &size);  


-Neophyte
Vectors whould be contiguously stored in memory. Its not yet in the standard, but is on the to do list and works in just about every STL implementation (double check yours to make sure).

To get the address of the memory stored by the vector use the same syntax as an array:


  std::vector<float> v;v.reserve (100);float *p;p = &v[0];  


Only do this to pass const pointers to functions, otherwise you could have issues if you start fudging the memory.
Thanks everyone for the help! I figured out the thing about saying &array[0], though I wasn''t sure if it was "correct" to do it, but I guess it is okay. That info about it becoming part of the standard was really useful! Thanks!

Rajan

This topic is closed to new replies.

Advertisement