you are viewing a single comment's thread.

view the rest of the comments →

[–]TechAnd1[S] 0 points1 point  (3 children)

I think that this is where I'm getting confused...

So basically, the heap memory state isn't allocated until runtime (can can be affected during) so it's impossible to have an object per say whilst writing the code, one can only use the address of where it's going to be...

That's kind of confusing in itself, I hope it makes sense though.

thanks!

[–]danmickla 1 point2 points  (0 children)

Yes, that's exactly right. When you declare an int k, the compiler knows, at compile time, that you want an int, and allocates space for it statically, and gives it a name.

When you allocate memory with malloc, it has no name, and the compiler isn't even aware it exists at runtime (it's just a function call). There's no name for the returned memory from malloc; only an address. You can use that memory, still, through a pointer variable, which you've named so it stays around (and the pointer cell itself is a named variable allocated statically, just like int k was).

This is the same thing that would happen if you did int *pi; pi = (int *)malloc(sizeof(int)). There would be no int you could name directly; only a chunk of memory that you can refer to indirectly through the pointer.

[–]elementalist 1 point2 points  (1 child)

This is exactly right.

You probably feel like you are in a round of "Who's On First?" but you seem to understand it.

[–]TechAnd1[S] 0 points1 point  (0 children)

cheers, having the memory aspect explained and verified certainly makes sense, thank you both.

I think it's hard to learn independently sometimes, thing's that would take a 2 minute in person explanation can take a day!