0

I am confused, while debugging code I am facing with some weird value 3440 for my int struct members. For example here is one function

struct Node
{
    int ptrCounter;
    void *value;
    struct Node *next;
};

typedef struct Node *Node;

struct SL
{
    Node front;
    CompareFunction compare;
    DestroyFunction destroy;

};

typedef struct SL* SLPtr;


SLPtr SLCreate(CompareFunction cf, DestroyFunction df)
{
    SLPtr slp = (SLPtr)calloc(1, sizeof(SLPtr));
    Node frontNode = (Node)calloc(1, sizeof(Node));
    frontNode -> ptrCounter = 1;
    frontNode -> value = NULL;
    frontNode -> next = NULL;

    slp -> front = frontNode;
    slp -> compare = cf;
    slp -> destroy = df;

    return slp;
}

When I am standing on the breakpoint at (return slp;) I see that my (frontNode -> ptrCounter;) has value 3440. Why is it so? Thanks

YohanRoth
  • 3,153
  • 4
  • 31
  • 58

1 Answers1

5

You are allocating the wrong amount of space. The sizeof must be the size of the thing being pointed to, not the size of the pointer.

To avoid this sort of error you can use the pattern ptr = calloc(N, sizeof *ptr);. In your case:

SLPtr slp = calloc(1, sizeof *slp);

Many experienced programmers feel that pointer typedefs make the code harder to read, so I would advise getting rid of SLPtr and just doing struct SL *, or SL * if you also do typedef struct SL SL;.

Node frontnode has the same error.

M.M
  • 138,810
  • 21
  • 208
  • 365
  • @PutinHuylo No. [Further reading](http://stackoverflow.com/questions/605845/do-i-cast-the-result-of-malloc) – M.M Sep 28 '14 at 02:05
  • 1
    To add to what @MattMcNabb said, `typedef`s usually are in place if you want your own custom data types for portability, or maybe for convoluted function pointer types that need to be exposed to external applications. Try to refrain from making simple typedefs if they are easy to read as it is. http://ieng9.ucsd.edu/~cs30x/rt_lt.rule.html – Cloud Sep 28 '14 at 02:16
  • @MattMcNabb Ok then. I just read The C Book that you should do this way : return (struct tnode *) malloc(sizeof(struct tnode)); when you return allocated space. And we study in our University that we must cast malloc/calloc pointer to an appropriate type. I am confused with this misconception – YohanRoth Sep 28 '14 at 02:25
  • @PutinHuylo your book is out of date, that is a style from the 1970's. See the link I posted earlier in the comment for an explanation. – M.M Sep 28 '14 at 02:27