Skip to content

[BUG] read access violation when using developer_tools/malloc_dbg #850

@sebbeutler

Description

@sebbeutler

Description

When using malloc_dbg.h to keep track of memory allocations, the program throw a read access violation. tmp was nullptr. in file malloc_dbg.c at line :

if (tmp->ptr == ptrToFree)

when calling malloc _dbg inside a loop.

This issue is happening because of the malloc_debug fonction.

	pos = inList(filename, line);
	if (pos == -1)    
	{
		// Add a new element in the mem_info list
		memoryInformation = addMemInfo(memoryInformation, ptrToReturn, bytes, line, filename, functionName);
		if (!memoryInformation)
		{
			free(ptrToReturn);
			return NULL;
		}
	}
	else           // If malloc was already called from the same file at the same line
	{
                // Here there are no call of [addMemInfo](https://github.com/TheAlgorithms/C/blob/cc241f58c253c533ac94e07151ef91a5ef7e5719/developer_tools/malloc_dbg.c#L40-L70) so the pointer that we return is not saved in the linked list
                // so we will never be able to free it later.
		editInfo(pos, bytes);
	}
	return ptrToReturn;

Expected behavior

ptrToReturn being added to the linked list

Actual behavior

only the sizeof ptrToReturn is saved into the list and it throws a read access violation

Possible fix

remove the inList() condition check and the editInfo() call

Steps to reproduce

Replace developer_tools/test_malloc_dbg.c main() by :

int main(int argc, char* argv[])
{
    int* test_list[5] = {NULL};

    for (unsigned i = 0; i < 5; i++)
    {
        test_list[i] = malloc(sizeof(int));
    }

    for (unsigned i = 0; i < 5; i++)
    {
        free(test_list[i]);
    }
    
    return 0;
}

Context

Got this bug when trying to allocate multiple blocks of memory in a loop and using malloc_dbg macros.

Additional information

No response

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type
    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions