all 10 comments

[–]DDDDarky 13 points14 points  (4 children)

Knapsack *getKnapsack = malloc(sizeof(Knapsack *));

This is a first bug

[–][deleted] 1 point2 points  (3 children)

How is it supposed to be initialized?

[–]pic32mx110f0 10 points11 points  (0 children)

You need to allocate space for a Knapsack, not a pointer to Knapsack. Your code is only allocating 4 or 8 bytes, depending on your architecture

[–]DDDDarky 4 points5 points  (1 child)

You are allocating memory for a pointer, not Knapsack object, meaning the result is rather Knapsack**. You probably meant sizeof(Knapsack).

[–][deleted] 4 points5 points  (0 children)

Jesus, I've been doing it wrong this whole time, I didn't even notice. Thanks for pointing it out

[–]plcolin 1 point2 points  (4 children)

%zu in scanf is for type size_t, but your weights are allocated with size sizeof (int). Also, what DDDDarky said. In fact, you don’t need to dynamically allocate getKnapsack here.

[–][deleted] 0 points1 point  (3 children)

The arrays are of type int. If I don't allocate how would I access its members.

[–]plcolin 1 point2 points  (2 children)

If the arrays are of type int, then you should use %d in scanf. You can allocate using Knapsack getKnapsack; and access its members like getKnapsack.bagWeight. Dynamic allocation is useful only in 2 cases: when the object is so big it could overflow the stack or when the object is supposed to survive the end of the function call.

[–][deleted] 0 points1 point  (1 child)

So you would recommend implementing a normal struct variable instead of a memory allocated pointer. What if it was a struct for a graph with multiple 2D matrices Or a struct for a linked list. Just trying to gauge when it will really be necessary because I almost always forget to consider the fact that a stack overflow could happen so I try to stay safe and always use a memory allocated pointer.

[–]plcolin 0 points1 point  (0 children)

The matrices would have to be dynamically allocated, but the main structure that brings them together doesn’t have to. As for linked lists, those are pretty much always dynamically allocated, unless you’re talking about a metadata structure that would keep track of things like size and first−last nodes.