Reputation: 23
I'm trying to add a frame to a linked list of such structures, but instead of adding a new structure to the list each time, the program adds nothing, can anyone tell me what the problem is? Or give me a better exercise method?
The structures:
typedef struct Frame
{
char* name;
int duration;
char* path;
} Frame;
// Link (node) struct
typedef struct FrameNode
{
Frame* frame;
struct FrameNode* next;
} FrameNode;
The functions:
FrameNode* addFrame(Frame* frame)
{
char name[100] = { 0 };
char path[100] = { 0 };
int dur = 0;
Frame* p = (Frame*)malloc(sizeof(Frame));
printf("*** Creating a new frame ***\n");
printf("Please insert frame path:\n");
fgets(path, 100, stdin);
path[strcspn(path, "\n")] = 0;
strcpy(p->path, path);
printf("Please insert frame duration <in miliseconds>:\n");
scanf("%d", &dur);
getchar();
p->duration = dur;
printf("Please chooce a name for a new frame:\n");
fgets(name, 100, stdin);
name[strcspn(name, "\n")] = 0;
strcpy(p->name, name);
while (list != NULL)
{
if (strcmp(list->frame->name, p->name) == 0)
{
printf("The name is already taken, Please enter another name\n");
fgets(name, 100, stdin);
name[strcspn(name, "\n")] = 0;
strcpy(p->name, name);
}
list = list->next;
}
free(p);
return p;
}
FrameNode* insertAtEnd(FrameNode** list, Frame* fr)
{
if (*list)
{
FrameNode* help = *list;
FrameNode* tmp = (FrameNode*)malloc(sizeof(FrameNode));
tmp->frame = addFrame(fr);
while (help->next != NULL)
{
help = help->next;
}
help->next = tmp;
}
else
{
list = (FrameNode*)malloc(sizeof(FrameNode));
FrameNode* tmp = (FrameNode*)malloc(sizeof(FrameNode));
tmp->frame = addFrame(fr);
list = tmp;
}
}
I really need help, I have to submit it by Sunday. If you notice any more problems please tell me Thank you to everyone!!!!!
Upvotes: 0
Views: 102
Reputation: 537
At the end of the addFrame
function you free p
, but then you return it.
So in the line tmp->frame = addFrame(fr);
in the function insertAtEnd
, you assign a pointer that has been freed already, whose contents are unknown.
The solution is to simply remove the line free(p)
in addFrame
, but make sure that you have a free'ing mechanism later in your program for this list.
Edit: also, I now see that in the line list = tmp;
, you are actually assigning a value to the local variable list
, and what you should be doing is *list = tmp
.
Upvotes: 0
Reputation: 1835
A separate struct for a linked list usually adds nothing but complexity. Why not just use:
struct my_frame {
struct my_frame *next;
char *name;
int duration;
char *path;
}
It reduces complexity and simplifies memory allocation.
A few personal preferences: I suggest using a prefix to prevent generic names like "frame". I also suggest dropping the typedef. It does nothing for you. It only adds obscurity. Drop the capitals in type names. If you want to program in C, learn C don't try to make it look like C++, C# or Java.
Upvotes: 1