I have this problem when reallocating memory. I have created a program which you can put information about diffrent grocery items. A small scale shopping list. I'm trying to make the list of items exapnd and shrink for every new item that is put in the list. For the first item it doesnt have any sort of problem when alloctaing and freeing tha old NULL memory. But when adding more items and at the same time trying to free the allocated memory the program triggers a break point at row 144. This is the message I get. "wntdll.pdb contains the debug information required to find the source for the module ntdll.dll" What am I doing wrong?
This is the function that I have created for the purpose.
void addSpace(struct GroceryItem** pitemList, int listLength)
{
int add = listLength 1;
struct GroceryItem * temp;
temp = NULL;
do {
temp = (struct GroceryItem*)realloc(*pitemList, add * sizeof(struct GroceryItem));
} while (temp == NULL);
if(listLength!=0)
free(*pitemList);
_CrtDumpMemoryLeaks();//Cheking for memory leaks
*pitemList = temp;
return;
}
I'm very new to programmaing so if there is any problems understanding my question report it and I will try to be more specific.
CodePudding user response:
Your primary problem here is the use of free
:
- Case where
realloc
expands the memory region: Heretemp
andpitemList
will contain the same address, so freeingpitemList
esentially freestemp
. Afterwards,temp
points to invalid memory. Solution: remove the call tofree
. - Case where
realloc
is relocating the memory region: Heretemp
will point to the new memory region, andpitemList
will be deallocated byrealloc
. Therefore, freeingpitemList
in your code leads to a double free. Solution: remove the call tofree
.
So in both cases, the solution is to not call free. More infor about realloc
can be found here: https://en.cppreference.com/w/c/memory/realloc
Also, running realloc
in the while loop will probably not lead to anything good. If realloc
fails once, you would probably just want to abort your program.
CodePudding user response:
do{}while(temp == NULL)
is very fishy. Basically this means "if the computer runs out of memory then hang the program".if(listLength!=0) free(*pitemList);
is plain wrong, simply remove this code.realloc
is the function responsible for freeing old memory if needed. It may also return an address which is the same as the one you passed.
Essentially you can rewrite and simply this function to:
void addSpace(struct GroceryItem** pitemList, int listLength)
{
int add = listLength 1;
struct GroceryItem * temp;
temp = realloc(*pitemList, add * sizeof(*tmp));
if(temp == NULL)
{
/* handle error - exit program etc */
}
*pitemList = temp;
}
Which in turn is just a thin function wrapper around realloc, so it's arguable if the function fills a purpose to begin with.