Chamiika Mahakumbura
Chamiika Mahakumbura

Reputation: 331

How to allocate memory to struct pointer using malloc.h header?

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

struct student
{
    char name[25];
    int age;
};

int main()
{
    struct student *c;

    *c =(struct student)malloc(sizeof(struct student));
    return 0;
}

What is the wrong with this code? I tried times by alternating this code to allocate memory to struct pointer. But this error comes when compiling:

testp.c:15:43: error: conversion to non-scalar type requested
  *c =(struct student)malloc(sizeof(struct student));
                                           ^

I'm using mingw32 gcc compiler.

Upvotes: 1

Views: 776

Answers (2)

Sourav Ghosh
Sourav Ghosh

Reputation: 134286

What is the wrong with this code?

Ans: First of all you change that "is" to "are", there are two major problems, atleast. Let me elaborate.

  • Point 1. You allocate memory to the pointer, not to the value of pointer. FWIW, using *c (i.e., de-referencing the pointer without memory allocation) is invalid and will result in undefined behaviour.

  • Point 2. Please do not cast the return value of malloc() and family in C. The cast you used is absolutely wrong and proves the authenticity of the first sentence.

To solve the issues, change

*c =(struct student)malloc(sizeof(struct student));

to

c = malloc(sizeof(struct student));

or, for better,

c = malloc(sizeof*c);   //yes, this is not a multiplication
                        //and sizeof is not a function, it's an operator

Also, please note, to make use of malloc() and family , you don't need the malloc.h header file. These functions are prototyped in stdlib.h.


EDIT:

Suggestions:

  1. Check for success of malloc() before using the returned pointer.
  2. Always free() the memory once the usage is over.
  3. The recommended signature of main() is int main(void).

Upvotes: 6

Varun Garg
Varun Garg

Reputation: 2654

This worked (on C and C++).
Since you originally included both tags.

change

*c =(struct student)malloc(sizeof(struct student));

to

c =(struct student*) malloc(sizeof(struct student));

Upvotes: 1

Related Questions