This is from an email response I just sent to a student asking about malloc()...
> my biggest fear is how do i get malloc working right, that is with my
> struct.
malloc() can be one of the trickier parts of C, simply because it
requires knowledge of pointers and indirection.
Basically, all malloc() does is tell the operating system to give your
program a certain number of bytes of memory. Remember that the argument
to malloc() is always interpreted as bytes. If you need to contain
anything other than character values, you need to use the sizeof() operator:
struct mystruct *ptr;
ptr = (struct mystruct *) malloc(sizeof(struct mystruct));
ptr will have one of two things: a pointer to a region of memory big
enough to hold a struct mystruct, or NULL. You *always* have to check
for NULL when you call malloc().
if (ptr == NULL) {
fprintf(stderr, "ZOMGWTF?");
exit(EXIT_FAILURE);
}
(You could use abort() instead of exit() if you want.)
When you access the resulting structure, you need to "indirect" through
the pointer. This is done with the asterisk operator:
int val;
val = (*ptr).val_field;
Of course, this is a common enough procedure to have a shortcut:
val = ptr->val_field;
One last thing to remember: everything you malloc(), you must free().
if (ptr != NULL) {
free(ptr);
ptr = NULL;
}
You don't have to explicitly set ptr to NULL, but it's a very good idea,
because freeing the same memory twice will generally make your program
crash. Likewise, freeing NULL will also make your program crash, hence
the if statement. (Memory allocation is the biggest source of bugs in C
programs, so it's worth a little bit of extra effort to make sure
everything is safe.)
If you have any further questions, I'll be in my 'office' tomorrow.
|