Archived

This topic is now archived and is closed to further replies.

sandrew

Freeing Memory! delete [] ....

Recommended Posts

ok! please dont laugh when u read my question! I am new to programming! I am trying to delete memory but I am not sure how! Example: unsigned char *bitmapImage; // bitmap image data unsigned char *heightmapData; // the map image data unsigned char *LoadBitmapFile(char *filename, BITMAPINFOHEADER *bitmapInfoHeader) // allocate memory for the bitmap image data bitmapImage = (unsigned char*)malloc(bitmapInfoHeader->biSizeImage); ..etc... return bitmapImage; } // SEE HERE BELOW!! void init() { heightmapData = LoadBitmapFile("heightmap/terrain.bmp", &bitmap1InfoHeader); // deallocate memory free(bitmapImage) // IS IT RIGHT! I DONT NEED IT ANYMORE, SO CAN I DELETE IT THIS WAY? } Now for example if I dont need the heightmapData too then how do I delete it? Note I am not using new or malloc see its declaration at the top!!!! should I use a simple for loop and set all to 0 or there is another way in C++! Actually setting an array to 0 means that we deallocate memory or not? Could I still use delete [] heightmapData even if I did not use the new operator? is it correct? How do I free memory currently reserved by the heightmapData array? Thanks for help! Edited by - sandrew on January 15, 2002 9:33:19 AM Edited by - sandrew on January 15, 2002 10:17:02 AM Edited by - felisandria on January 15, 2002 10:52:41 AM

Share this post


Link to post
Share on other sites
Yeah you are right, when you use malloc() to allocate some memory you must clear it with free() when you are done, but be sure to set the pointer to zero when you are done so that another call to free() on that pointer will not result in a program crash like so

  
free (bitmapImage);
bitmapImage=NULL;


Dark Star
UK

P.S.

I''m not sure if the free function automatically sets the pointer to set to NULL by itself, but there is no harm assigning NULL to the pointer urself just to be safe. Also if u use new be sure to compliment it with delete command and not to use the free and new and delete interchangably.


Share this post


Link to post
Share on other sites