Don't understand malloc issue

Go To Last Post
3 posts / 0 new
Author
Message
#1
  • 1
  • 2
  • 3
  • 4
  • 5
Total votes: 0

Hi there, i have code:

void ReadMultipleByte(uint8_t Addr, uint8_t amount, uint8_t *result)
{
	uint8_t *packet;
	packet = (uint8_t *) malloc(amount);
	packet[0] = Addr;
	i2cMasterSendNI(0xD0, 1, packet);
	i2cMasterReceiveNI(0xD0, amount, packet);
	memcpy(result,packet,amount);
	free(packet);
}

void USART_Transmit(uint8_t data_to_transmit)
{
	// blah blah blah
	// code for sending through serial line
	// blah blah blah
	UDR = data_to_transmit;
}

uint8_t USART_Receive(void)
{
	// blah blah blah
	// code for receiving from serial line
	// blah blah blah
	return UDR;
}

void main()
{
	uint8_t somespace[10] = {0};
	uint8_t i;
	while(1)
	{	ReadMultipleByte(USART_Receive(),10,somespace);
		for(i=0;i<10;i++)
			USART_Transmit(somespace[i]);
	}
}

Notice the "malloc" and "free" part, "malloc" was used to allocate 'amount' bytes of space and assigned it to 'packet', right? and "free" was used to release the allocated space before so it can be used for another process. The question is what if i don't "free" the 'packet' like function below? if i called function 'ReadMultipleByte' many times what will be done? will my RAM exhausted?

uint8_t *ReadMultipleByte(uint8_t Addr, uint8_t amount)
{
	uint8_t *packet;
	packet = (uint8_t *) malloc(amount);
	packet[0] = Addr;
	i2cMasterSendNI(0xD0, 1, packet);
	i2cMasterReceiveNI(0xD0, amount, packet);
	return packet;
}

Thanks.

KISS - Keep It Simple Stupid!

  • 1
  • 2
  • 3
  • 4
  • 5
Total votes: 0

Surely any library documentation of malloc() will answer your question.

You will eventually run out of memory, and malloc() will return NULL. Your code does not check for NULL so you will CRASH.

David.

  • 1
  • 2
  • 3
  • 4
  • 5
Total votes: 0

Btw., your code would be much better using alloca() rather than malloc().
It will allocate the storage for the packet off the stack, much like a
local variable would. As such, it's not as expensive to do as malloc()
is (because it wants to allocate from a global pool), and it has the
added bonus of automatically freeing up that storage upon exiting the
function.

Jörg Wunsch

Please don't send me PMs, use email if you want to approach me personally.