Unable to allocate memory with k_malloc

nRF Connect SDK 2.3.0 on nRF52840DK

I am trying to add a fifo to my application but when trying to allocate the memory for the data item, k_malloc always returns NULL no matter what I do. The data item I can confirm a size of 8, and my CONFIG_HEAP_MEM_POOL_SIZE is set to 4096 in my config file. 

K_FIFO_DEFINE(my_fifo);

struct data_item_t {
	void *fifo_reserved;
	uint32_t data;
};
static void uart_cb(const struct device *dev, struct uart_event *evt, void *user_data)
{
	uint32_t* rsp_p = (uint32_t *) evt->data.rx.buf;
	
	int bytes_written;
	switch (evt->type) {

	case UART_RX_RDY:

		//Get controller input response from UART RX buffer
		struct data_item_t *buf = k_malloc(sizeof(*buf));//TODO k_malloc returns NULL
		
		uint32_t rsp_32 = *rsp_p;
		if (buf == NULL){
			LOG_INF("Unable to allocate memory");
			break;
		}
		int bytes_written = snprintf(&buf->data, 4, "%x", rsp_32);
		k_fifo_put(&my_fifo, buf);


		break;
	case UART_RX_DISABLED:
		uart_rx_enable(dev ,rx_buf,sizeof rx_buf,RECEIVE_TIMEOUT);
		break;
		
	default:
		break;
	}
}
Parents
  • Hi Sam,

    Please make sure that nothing else is utilising or taking up the heap memory. Please try increasing the heap memory to, say, 8192 for instance just to verify whether the problem lies with the heap memory pool. Do let me know if you still get the problem.

    Regards,

    Priyanka

  • Thank you Priyanka, this was actually a partial solution. I had to adjust the heap memory size to a ridiculous amount to notice that I was actually able to allocate SOME memory before it ultimately returns NULL again. This was due to my not realizing that my application was trying to allocate memory faster than it was freeing it up. The k_free instruction I had was not looping as fast as I had thought originally.

Reply
  • Thank you Priyanka, this was actually a partial solution. I had to adjust the heap memory size to a ridiculous amount to notice that I was actually able to allocate SOME memory before it ultimately returns NULL again. This was due to my not realizing that my application was trying to allocate memory faster than it was freeing it up. The k_free instruction I had was not looping as fast as I had thought originally.

Children
Related