Day#42 'C' Coding Challenge

Day#42 'C' Coding Challenge

Is there any issue with the below code? If yes, please, point out.

#include <stdio.h>
#include <malloc.h>
struct student {
char *name;
int marks; float GPA; };
struct student *record;
void main() {
record = (struct student *)malloc(sizeof(struct student));
record->name = (char *)malloc(30);
}

------------------------------------------------------------------------

The above code tests below scenarios:

1. Structure declaration
2. Pointer variable within a structure
3. Structure variable definition
4. Assigning a memory to the pointer variable within a structure
5. using malloc() to allocate memory

------------------------------------------------------------------------

The above code is correct and there are no issues. 

Structure student has a 3 variables and character pointer is one among them. While assigning memory to the struct, the entire structure has been used. However, memory has been assigned separately to character variable. While this is OK, when memory is to be freed, it has be done separately for the name.

The above code can be improved by adding additional code to check if malloc() has allocated memory or not. Also, free() function can be used to free up the memory.

Post a Comment

0 Comments