Using Malloc in C: Writing to a Dynamic Memory Buffer

advertisements

I have the following structure in C

struct _MY_LIST
{
    short sRecNum;
    short sConfirm;
    short sFCount;
}my_list;

How do I use malloc to allocate memory for this structure as well to write this structure to dynamic memory?


You've defined a structure and a variable composed of the structure, but you need to define a pointer to that structure instead.

Pointers are a difficult topic to master and what I'm about to post will give you a sharp knife to play with -- but you could end up cutting yourself with it if you don't tread lightly! Learning them will take far more than a single SO answer could provide, but at least be sure to read the comments I sprinkled into this code snippet.

struct _MY_LIST
{
    short sRecNum;
    short sConfirm;
    short sFCount;
} *my_list_pointer; /* the asterisk says this is a pointer */

/* dynamically allocate the structure */
my_list_pointer = malloc(sizeof(*my_list_pointer));

/* required error checking! */
if (my_list_pointer == NULL) {
    /* do whatever you need, but do _not_ dereference my_list_pointer */
    exit(-1);
}

/* write to the structure */
my_list_pointer->sRecNum = 50;

/* read from the structure */
short the_record_number = my_list_pointer->sRecNum;

/* when finished with the allocation, you must release it */
free(my_list_pointer);

/* now, you must NOT dereference my_list_pointer anymore unless you malloc it again! */