Leran Dagash
Leran Dagash

Reputation: 65

Can someone tell me why this isn't working?

So I'm making a program to scan the name and grades of a number of students and then show me all of the students with an average of 85+. I'm required to use structures and the instructions say I have to dynamically allocate memory for the names with the help of the strlen function.

#include<stdio.h>
#include<stdlib.h>
#include<string.h>

typedef struct stud
{
    char *name;
    int marks[4];
    float avg;
}student;


student* Create_Class(int);
void Avg_Mark(student*);
void Print_One(student*);


int main()
{
    int size, i;
    student *arr;
    printf("\nEnter the number of students: ");
    scanf("%d", &size);
    arr = (student*)malloc(size * sizeof(student));
    arr = Create_Class(size);
    for (i = 0; i < size; i++)
    {
        if ((arr + i)->avg > 85)
            Print_One(arr + i);
    }
    for (i = 0; i < size; i++)
        free((arr[i].name));
    free(arr);
    return 0;
}

student* Create_Class(int size)
{
    struct stud *Arr;
    int i, j, k;
    char YourName[51];
    int length;
    Arr = (struct stud*)malloc(size * sizeof(struct stud));
    for (i = 0; i < size; i++)
    {
        printf("Enter your name: ");
        scanf(" %s", YourName);
        length = strlen(YourName);
        (Arr + i)->name = (char*)malloc(length * sizeof(char));
        for (k = 0; k < length; k++)
            (Arr + i)->name[k] = YourName[k];
        (Arr + i)->name[k] = '\0';
        printf("Enter your marks: ");
        for (j = 0; j < 4; j++)
            scanf("%d", &(Arr + i)->marks[j]);
    }
    for (i = 0; i < size; i++)
        Avg_Mark(Arr + i);
    return Arr;
}


void Avg_Mark(student* s)
{
    int i;
    float sum = 0;
    for (i = 0; i < 4; i++)
    {
        sum += s->marks[i];
    }
    s->avg = sum / 4;
}


void Print_One(student* s)
{
    printf("The average of %s is %.1f\n", s->name, s->avg);
}

It seems the problem is with freeing the name field pointer in the main function. Can someone tell me what went wrong? The code itself is pretty straightforward so if anything is unclear feel free to ask and I'll try to be as detailed as possible.

Upvotes: 1

Views: 118

Answers (1)

kiran Biradar
kiran Biradar

Reputation: 12742

There are two issues in your code.

  1. You are overwritting the arr memory by calling create_class

    arr = (student*)malloc(size * sizeof(student)); arr = Create_Class(size);

    This will lead to memory leak, so just remove arr = (student*)malloc(size * sizeof(student));.

  2. You are not allocating enough memory to your name field.

    length = strlen(YourName); (Arr + i)->name = (char*)malloc(length * sizeof(char));

    should be length = strlen(YourName)+1; to hold null char.

Upvotes: 2

Related Questions