-1

This is my code:-

typedef struct Frame
{
    char* name;
    unsigned int duration;
    char* path;  // may need to scan (with fgets)
}frame_t;

typedef struct Link
{
    frame_t* frame;
    struct Link* next;
}link_t;

void addNewFrame(void)
{
  link_t* newLink = (link_t**)malloc(sizeof(link_t*));
  printf("                *** Creating new frame ***\n\n");
  printf("Please insert frame path:\n");

  //  newLink->frame->name = (char*)malloc(sizeof(char) * MAX_LEN);

  fgets(newLink->frame->name, MAX_LEN,stdin);
  printf("%s", newLink->frame->name);
}

I just need to add a data to name variable in the "Frame" link list, please help me by reviewing this code.

OmG
  • 18,337
  • 10
  • 57
  • 90
yehezkel horoviz
  • 198
  • 3
  • 10

2 Answers2

1

You want to allocate the right types here:-

link_t* newLink = malloc(sizeof(link_t));  //Pointer to Link st
if(newLink){
    newLink->frame = malloc(sizeof(frame_t)); //Pointer to frame member
    if(newLink->frame){
        newLink->frame->name = malloc(sizeof(char) * MAX_LEN); //Pointer to name member
        if(newLink->frame->name){
            //Rest of your code
        }
    }
}

EDIT:-
1. As pointed out in comments there's no need to cast the pointer returned by malloc()
2. Another very imp point you may want to check validity of the pointers before de-referencing them

Zakir
  • 2,222
  • 21
  • 31
0

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.
geckos
  • 5,687
  • 1
  • 41
  • 53