0
votes

I'm trying to write a program for students linked list in C. Here is the struct:

typedef struct student *studp;
typedef struct student{
    int number;
    char *name;
    char *date;
    unsigned grade;
    studp next;
}stud;

Now I want to write a function which creates new node and assign values to members. I'm not sure how to do it, here is the function:

studp create_stud(int number, char *name, char *date, unsigned grade){
studp item = (studp)malloc(sizeof(stud));
if(!item){
    printf("Cannot allocate memory\n");
    exit(1);
}
item->number = number;
item->name = .....


return item;

} how should I assign the text to the member name and date? can I use the operator '=':

item->name = name;

or I should allocate the memory with malloc() ? and if I use malloc() should I free the pointer in the and of the program or I just can release the node? Thanks!

2
Hiding pointers under typedef is evil. - user2736738
What do you mean> - Tohar Pingley
And calling studp that looks confusingly like strdup() was going to make me crazy. - Iharob Al Asimi
@ToharPingley That you should never do typedef POINTER_TYPE *NON_POINTER_TYPE because it's confusing. - Iharob Al Asimi
@IharobAlAsimi Got it. - Tohar Pingley

2 Answers

2
votes
item->name = strdup(name);

This will do the trick. In case you don't have this (strdup is a POSIX thing) allocate memory and then use strcpy/memcpy to copy the string pointed by name.

Don't hide pointers inside typedef it's easier to maintain in large codebase - you always have to look back to get what it's type is to write correct code.

Don't cast the return value of malloc and check the return value of strdup just like you did for malloc. Also free the memory allocated using malloc and strdup when you are done working with it.

To show you an example. (Illustration)

stud* item = malloc(sizeof *item);
if(NULL == item){
    perror("Cannot allocate memory\n");
    exit(EXIT_FAILURE);
}
...

free(item->name);
free(item->date);
/* whatever you have allocated */
free(item);

Edit: In case strdup is not there.

item->name = malloc(strlen(name)+1);
if(!item->name){
   perror("malloc");
   exit(EXIT_FAILURE);
}
memcpy(item->name, name, strlen(name)+1);
0
votes

Your structure contains char* members. They can point to a string, but they can't contain a string. In order to copy over those string members, you need to allocate buffers for the char* fields in the new structure, then strncpy() over the contents.

It's your responsibility to free all memory that you allocate. Think of it as if every malloc call needs a matching free. I recommend writing a corresponding delete_stud function that handles cleanup. It can free the memory associated with the structure, plus any buffers allocated for the char* members.