Asking for help

I use mosquitto on Android, so REAL_WITH_MEMORY_TRACKING is not defined.
Due to unknown reason, my application crashed(invalid chunk state when deallocating address 0x200006d77d42610)
I want to know why the code below(mosquitto-2.0.14/lib/memory_mosq.c)

void mosquitto__free(void *mem)
{
#ifdef REAL_WITH_MEMORY_TRACKING
	if(!mem){
		return;
	}
	memcount -= malloc_usable_size(mem);
#endif
	free(mem);
}

is not written as below?

void mosquitto__free(void *mem)
{
	if(!mem){
		return;
	}
#ifdef REAL_WITH_MEMORY_TRACKING
	memcount -= malloc_usable_size(mem);
#endif
	free(mem);
}

Thanks!

The code is written as an improvement. According to the POSIX standard (in case of free) and documentation of the non-standard malloc_usable_size both function may be invoked with a null ptr. The malloc_usable_size function will return 0 and the free function should simply perform no operation. But internally both function would need to check on a null pointer and additionally we would perform a (relative) expensive atomic increment on memcount, which normally requires some cache invalidations.

But as your pointer is not null the other implemetation of the function would not help to avoid the crash. And the Android free function is implemented compliant with the standard and does allow a null pointer agrument.
Due to my experience you most likely have a memory fault somewhere in your code. Either a double free, use after free or a write after free (deleteing the chunk state). It might be a good idea to run your code with some memory check tools like using a clang ASAN build or a valgrind memcheck.

Hi!
Thanks for your reply!

I think this crash may be in mosquitto code itself.

I see that in C language, when freeing the Dynamic Memory Allocated, the pointer’s value would not be changed and the pointer’s value should be set to NULL manually.
But I found that in mosquitto’s source code, when freeing the Dynamic Memory Allocated, the pointer’s value has never been set to NULL manually.

I want to know if it is the reason why my application crashed.

Please help to guide, thanks very much!

Hi Tim,

To be of any help you’ll have to be more specific about where this is occurring. It might also be worth upgrading to 2.0.18 as well.

Regards,

Roger