First. You don't need to cast void *
so (link_t **)malloc(...
can be only malloc(...
.
Second. You allocated enough memory for a pointer not for a struct. I think you mean malloc(sizeof(link_t))
or even better malloc(sizeof(*newLink))
Third newLink->frame
is a pointer so you need to allocate data for it too, newLink->frame = malloc(sizeof(frame_t))
Fourth newLink->frame->name
is still a pointer so you need to allocate data for it too. newLink->frame->name = malloc(MAX_LEN)
The confusion that you are doing is pretty common. When you say type *something
you are allocating a pointer to type
in the stack. A pointer needs to point to somewhere else or NULL, or bad things happen. This applies to structures too. If your structure has a pointer member you need to point it to somewhere else. The somewhere else is where the real "type" object resides.
This also applies to arrays. If you say 'int foo[10]' you are allocating ten integers in the stack. If you say int *foo[10]
you are allocating ten pointers in the stack. If you say int **foo
you are allocating one pointer in the stack. Again all pointers need to be initialized, I mean, they need to point to some valid object, allocated somewhere else in the memory.
I hope this helps.
Some other points.
- Always check pointer coming from malloc, if allocation failed you'll receive NULL. Dereferencing NULL will break your program.
- Always initialize memory coming from malloc, fill it with zeros or something.
- Don't use
_t
suffix, is POSIX reserved.
- I didn't test any of this.