[Solved] C memory allocation in student structure not working


The API is confusing:

What is namelen ?

  • is it the length of the initial prefix of name that is the name of the student? In this case you should allocate one extra byte for the null terminator and copy the name appropriately.
  • is it the maximum length for the student name? Again if this a the length, not the size, you need an extra byte for the null terminator.
  • in any case sizeof(namelen) is inappropriate.

What does student_alloc() do?

Similarly, the size passed to malloc() to allocate the student structure should be that of struct student or more reliably that of the type pointed to by the destination pointer.

Here is a corrected version:

struct student *student_init(struct student *student, const char *name, size_t namelen,
                             struct student_id stud_id, student_complete stud_complete) {

    struct student *initialized_student = malloc(sizeof(*initialized_student));
    char *s_name = calloc(namelen + 1);

    if (initialized_student && s_name && student_alloc()) {
        strncat(s_name, name, namelen);
        initialized_student->s_name = s_name;
        initialized_student->s_id = stud_id;
        initialized_student->s_complete = stud_complete;
        return initialized_student;
    } else {
        free(initialized_student);
        free(s_name);
        return 0;
    }
}

solved C memory allocation in student structure not working