Help with map server leak

bWolfie

I'm the man
Messages
850
Points
0
Location
Alberta, Midgard
Github
bWolfie
Emulator
I made this command to retrieve all of an item from storage.

This line char *item_name =(char *)aMalloc(ITEM_NAME_LENGTH*sizeof(char)); causes memory leak. How to fix it?

Code:
	struct item_data *i_data = itemdb->exists(nameid);

	if (i_data == NULL) {
		clif->message(fd, "Invalid Item ID.");
		return false;
	}

	char *item_name =(char *)aMalloc(ITEM_NAME_LENGTH*sizeof(char));
	memcpy(item_name, i_data->jname, ITEM_NAME_LENGTH);

	char output[100];
	sprintf(output, "Retrieved %d '%s' from storage.", i, item_name);
 
Either add a

aFree(item_name);


or better use a stack allocation instead of malloc

Code:
char item_name[ITEM_NAME_LENGTH];
 
after sprintf, add

aFree(item_name);


and why memcpy? server may crash if name too short. probably better strncpy or safestrncpy

 
Thanks for the responses. I don't know why I use memcpy, not so advanced on coding. I just copied an existing structure I found in source code.

I used safestrncpy in new version and no leaks.

Code:
	char item_name[ITEM_NAME_LENGTH], output[100];
	safestrncpy(item_name, i_data->jname, ITEM_NAME_LENGTH);
	sprintf(output, "Retrieved %d '%s' from storage.", i, item_name);
 
Last edited by a moderator:
Back
Top