Jump to content
  • Advertisement

Archived

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

gregd

Memory Allocation problem

This topic is 5530 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

The problem I'm facing now is, when I pass a struct pointer, to a function, and try to allocate memory with malloc for it, from inside of that function, it doesn't seem to allocate memory to the struct I was passing to this function. malloc doesn't return NULL, so, it did allocate some data. but after calling the function (ptr_structdata[(i)] == NULL), where i is just an index into the struct. (i allocate a few structs actually...its an array, that might be the problem, but im not sure) however, when i pass the pointer to that function by reference, it seems to work. what could be wrong? --- here is the code:

// doesnt work:
void REF_MallocItemPointer (ref_item_t *dataptr, int datacount)
{
	if ( (dataptr = (ref_item_t *) malloc ((REF_ITEM_HEADER_SIZE + 4) * datacount)) == NULL )
	LogErr("; REF_MallocItem: insufficient memory!\n");
}

// works:
void REF_MallocItemReference (ref_item_t &dataptr, int datacount)
{
	if ( (dataptr =
		 (ref_item_t *) malloc ((REF_ITEM_HEADER_SIZE + 4) * datacount)) == NULL)
			LogErr("; REF_Build: malloc: insufficient memory!\n");
}

typedef struct tagItem
{
	char	ri_name[8];			// 8-char name derived from the filename
	dword	ri_size;			// size of the header + all data, in bytes
	dword	ri_type;			// REF_PIC, REF_FONT, REF_TEXT, ...
	word	ri_width;			// 
	word	ri_height;

	word	ri_data_type;		// REF_8BIT, REF_24BIT, REF_16BIT, REF_32BIT
	word	ri_data_flag;		// 
	void   *ri_data;			// data
} ref_item_t;


ref_item_t *REF_ITEM;

// WORKS:
REF_MallocItemReference (*REF_ITEM, 2);

pseudo: at this point, REF_ITEM[0] != NULL;


// DOESN'T WORK:
REF_MallocItemPointer (REF_ITEM, 2);

pseudo: at this point, REF_ITEM[0] == NULL;



As you can see, im actually using the asterisk to "dereference" a pointer, so that the reference of the data is passed to the function 

[edited by - gregd on April 30, 2003 11:29:22 PM]    

Share this post


Link to post
Share on other sites
Advertisement
you''re passing the pointer by value. Remember? When you pass an argument, a copy of it is made when it is passed into the function. You need to use either a reference to a pointer (in C++), or a pointer to a pointer. Assuming you do the second, your call would look like *dataptr = malloc(stuff).


How appropriate. You fight like a cow.

Share this post


Link to post
Share on other sites

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

Participate in the game development conversation and more when you create an account on GameDev.net!

Sign me up!