I'm having newbish trouble dynamically allocating structs. For a small library I'm writing, I have a typedef'ed struct containing a number of pointers. These structs are supposed to be an opaque structure representing the history of visited locations in an as-of-yet nonexistent file-manager.
To get a new one of these structures, I provide a function, shown below.
Code:
history_instance *history_new_instance(guint16 maxSize)
{
history_instance newInstance,
*returnInstance;
/*NOTE: May get better performance by using presized arrays to avoid
too frequent reallocs.*/
newInstance.theHistory = g_ptr_array_new();
newInstance.maxSize = (guint16*)malloc(2);
newInstance.currentLoc = (guint16*)malloc(2);
newInstance.lastLoc = (guint16*)malloc(2);
/*If any are NULL, malloc failed*/
if(newInstance.theHistory && newInstance.maxSize && newInstance.currentLoc &&
newInstance.lastLoc)
{
if(!newInstance.theHistory)
{free(newInstance.theHistory);}
if(!newInstance.maxSize)
{free(newInstance.maxSize);}
if(!newInstance.currentLoc)
{free(newInstance.currentLoc);}
if(!newInstance.lastLoc)
{free(newInstance.lastLoc);}
return NULL;
}
else
{
returnInstance = malloc(sizeof(history_instance));
if (returnInstance)
{return NULL;}
else
{
*(newInstance.maxSize) = maxSize;
*(newInstance.currentLoc) = 0;
*(newInstance.lastLoc) = 0;
*returnInstance = newInstance;
return returnInstance;
}
}
}
It creates a struct on the stack, initializes it, mallocs a struct, and copies the stack data into the malloced struct.
The trouble is that later, any reference like "theInstance->theHistory" segfaults, where theInstance is a pointer to one of these returned structs. How am I initializing these structs incorrectly?
Thanks for your help.