gbadev.org forum archive

This is a read-only mirror of the content originally found on forum.gbadev.org (now offline), salvaged from Wayback machine copies. A new forum can be found here.

C/C++ > malloc question

#168760 - moonlightcheese - Wed May 20, 2009 9:01 pm

if i declare a pointer to an object in a function and use malloc to allocate space for the size of the object... does the object die at the end of the function?

ex.
Code:

typedef struct {
     int* foo;
} bar;

void myFunc(bar* myBar) {
     int* myInt=malloc(sizeof(int));
     *myInt=4;
     myBar->foo=myInt;
}

int main() {
     bar* theBar=malloc(sizeof(bar));
     myFunc(theBar);   //would theBar contain a pointer to an integer 4?
     return 0;
}


i think malloc'd memory isn't free'd at the end of a function, but i'm asking to make sure i'm not mucking things up. if i'm reading this right, it looks like memory that is claimed with malloc is reserved until explicitly free'd... right?

#168761 - Dwedit - Wed May 20, 2009 9:06 pm

Yep, it doesn't die until you kill it.

Welcome to the world of Memory Leaks, whenever you forget to free something you've allocated.
_________________
"We are merely sprites that dance at the beck and call of our button pressing overlord."

#168762 - moonlightcheese - Wed May 20, 2009 9:10 pm

Dwedit wrote:
Yep, it doesn't die until you kill it.

Welcome to the world of Memory Leaks, whenever you forget to free something you've allocated.

cool thanks.

#169087 - elyk1212 - Sun Jun 14, 2009 5:58 pm

The easiest way to remember this is just to think of memory existing in two different spaces: Heap and stack space.

Stack space are local variables that are auto created when entering a block
e.g

Code:

{
   int temp;

}


At the end of the block, temp's memory space will be reclaimed and popped off the Stack.


However,

Code:

{
   Object* temp = new Object();
   int* temp2 = (int*)malloc(sizeof(int));
}

........In both of these cases, memory is allocated in Heap space (a dynamic, at times fragmented, memory space). Anytime you allocate space in this way you will have to worry about reclaiming them..


Have you ever looked into Boost shared pointers? These are counted and tracked pieces of memory, that can auto delete/free the entire object, type etc, that the pointer/array/etc is pointed to when no more references to the said memory exist.

They work pretty well, and are worth a look.

#175748 - erana_ - Thu Jan 27, 2011 9:03 pm

If you pass : &theBar to your function you get stack speed. Not just heap flipping mallocs which mess up your fine memory.