0

I have a problem with a push function. It's a simple push function for stack structure but most of the time doesn't work. It only works when debugging. This is the function:

tError favoriteStack_push(tFavoriteStack *stack, tFavorite favorite) {
    //assert(stack!=NULL);

    tFavoriteStackNode* tmp;

    //mem_allocation of new node
    tmp=(tFavoriteStackNode*)malloc(sizeof(tmp));

    if(tmp==NULL)
        return ERR_MEMORY_ERROR;

    //copying element to new node
    tmp->e=favorite;

    //pointing next to previous first element
    tmp->next=stack->first;

    //new node is the new first node
    stack->first=tmp;

    return OK;

}

I can't see the mistake. I would appreciate some help.

Thanks

pixel
  • 9
  • 1

1 Answers1

3

sizeof(tmp) will return the size of the pointer, not the size of the object, maybe sizeof(*tmp), but the best in my opinion is

tmp=(tFavoriteStackNode*)malloc(sizeof(tFavoriteStackNode));

Alberto Sinigaglia
  • 12,097
  • 2
  • 20
  • 48
  • 1
    That's it. Is sizeof(*tmp) instead of sizeof(tmp). Thank you very much!! – pixel Nov 13 '19 at 12:15
  • what i mean is that `tmp=(tFavoriteStackNode*)malloc(sizeof(tmp));` should become `tmp=(tFavoriteStackNode*)malloc(sizeof(tFavoriteStackNode));` – Alberto Sinigaglia Nov 13 '19 at 12:17
  • 2
    The `tmp=malloc(sizeof(*tmp));` form (no cast) is generally recommended. See https://stackoverflow.com/questions/605845/do-i-cast-the-result-of-malloc – Petr Skocik Nov 13 '19 at 12:22
  • 1
    People recommend `sizeof(*tmp)` since you don't have to write the type twice. But you do have to write the variable name twice. – user253751 Nov 13 '19 at 14:40
  • 2
    @user253751 It doesn't matter much if you're `malloc`ing in an initialization: `t *p = malloc(sizeof(t));`, where the type on the left and the type in the sizeof are right next to each other => easy to verify the `t` matches the `sizeof(t)`. But you could also have `t *p; /*...code...*/ p = malloc(sizeof(t))` and then if the declaration changes to `t1 *p`, the `malloc` call will be wrong and the error might not be easy to spot. `t *p; /*...code...*/ p = malloc(sizeof(*p));` won't have that problem. – Petr Skocik Nov 13 '19 at 16:44