Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Dynamic memory allocation | Unable to write on location

NOTE: Sorry if this is duplicate but i haven’t found any case which is similar to mine.

I am working on a C language project and I am not good at this. I am a very noob at dynamic memory allocation. So the issue I am facing is that when I create an instance of a structure which is given below

typedef struct temp_ {
    Household data;
    struct temp_ * next;
}Node, *NodePtr;

by this way it or many others I have tried so far

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

NodePtr makeNode(Household num){
    NodePtr ptr = (NodePtr) malloc(sizeof(NodePtr));
    ptr->data = num;
    return ptr;
}

So I get different types of errors that I can not understand.
If anyone can help it will be a great pleasure.

>Solution :

  1. Never hide pointers behing typedefs. It is extremely error prone. In your code you do not allocate enough memory, thus segfault.
  2. Use objects not types in sizeof
typedef struct temp_ {
    Household data;
    struct temp_ * next;
}Node;

Node *makeNode(Household num){
    Node *ptr = malloc(sizeof(*ptr));
    if(ptr) ptr->data = num;
    return ptr;
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading