NCS 1.6.1 at_cmd lib memory allocation and freeing question

Hi, 

I realise this is now quite an old version of the SDK and this particular library is no longer supported, but we have not yet migrated our project (I did try once, but seemed easier to completely rewrite it). 

In at_cmd.c line 362

    command.cmd = k_malloc(strlen(cmd) + 1);
	if (command.cmd == NULL) {
		return -ENOMEM;
	}
	strcpy(command.cmd, cmd);

	command.resp = NULL;
	command.callback = handler;
	command.flags = AT_CMD_BUF_CMD;

	ret = k_msgq_put(&commands, &command, K_FOREVER);
	if (ret) {
		return ret;
	}

	load_cmd_and_write();

Memory is allocated to command.cmd using k_malloc(). It is freed in "load_cmd_and_write()", but there is a chance k_msgq_put could return an error. Before it returns should there be a free?

ret = k_msgq_put(&commands, &command, K_FOREVER);
if (ret) {
	k_free(command.cmd);    // EDIT
	return ret;
}

I initially thought that would be a quick fix, but I saw there is a thread - "socket_thread_fn" that runs "load_cmd_and_write()" but I am not sure whether it will actually free this memory or not. When it is freed, it calls to free current_cmd.cmd, which is populated by k_msgq_get(), so it depends on how k_msgq_put behaves when it fails - however I cannot find the source code for this to work it out.

For background - I know there is an issue in either my code or the SDK with a memory leak, and there has been for years, but I have never been able to find it. I get a consistent reboot after a number of network/mqtt connections. The problem with finding it however, is that it takes a lot of connections to happen. If I have a schedule set up sending messages every 5 minutes, it takes about 36 hours to happen, if I set that to every 10 minutes 72 hours. It doesn't seem to make a difference if I set different stack sizes on my threads, and it never happens in the exact same bit of code, so I do think there is something in the sdk. 

Thanks, 

Damien

Related