From Contiki’s github Wiki
Here is an example of how to use the managed memory allocator:
#include "contiki.h"
#include "lib/mmem.h"
static struct mmem mmem;
static void
test_mmem(void)
{
struct my_struct {
int a;
} my_data, *my_data_ptr;
if(mmem_alloc(&mmem, sizeof(my_data)) == 0) {
printf("memory allocation failed\n");
} else {
printf("memory allocation succeeded\n");
my_data.a = 0xaa;
memcpy(MMEM_PTR(&mmem), &my_data, sizeof(my_data));
/* The cast below is safe only if the struct is packed */
my_data_ptr = (struct my_struct *)MMEM_PTR(&mmem);
printf("Value a equals 0x%x\n", my_data_ptr->a);
mmem_free(&mmem);
}
}
The example above shows a basic example of how the managed memory
library can be used. On line 4, we allocate a variable, mmem, that
identifies the managed memory object that we are about to allocate. On
line 13, we use the mmem variable as an argument for mmem_alloc() to
allocate space for a structure of sizeof(my_data) bytes. If the
allocation succeeded, we copy the values from an existing structure
into the allocated structure, pointed to by MMEM_PTR(&mmem).
Individual members of allocated structure can then be accessed by a
type cast of MMEM_PTR(&mmem) to struct my_struct *, as shown on line
20. Note that the cast is only safe if the struct is packed. The managed memory is finally deallocated on line 21 by calling
mmem_free().
.
EDIT:
From the code you've pasted in the comments, there is no need to use malloc
or the mmem
-module. Just allocate on the stack. Maybe try something like this instead:
/* Allocate memory on the stack */
char sent[120];
/* Manipulate strings */
strncpy(sent , "reqid" , 5);
strncat(sent, "|", 1);
/* Send UDP packet */
uip_udp_packet_send(mcast_conn, sent, strlen(sent));
/* Print out string sent */
printf(" (msg: %s)\n", sent);
EDIT 2:
Here is a page on heap vs stack. and here is a stackoverflow question about dynamic allocation on embedded devices and the problems it involves.