Search code examples
cstructdynamic-memory-allocation

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

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;
    }