I'm a bit confused about the difference between when I just declare a variable such as:
int n;
and dynamically assigning memory to a variable using "new" such as:
int m = new int;
I noticed just from working on a simple linked list project that when I'm inserting a new value in the form of an node object, I have to dynamically create a new node object and append the desired value to it and then link it to the rest of my list. However.. in the same function, I could just define another node object, ex. NodeType *N. and traverse my list using this pointer. My question is.. when we just declare a variable, does memory not get assigned right away.. or what's the difference?
Thank you!
Prefer automatic storage allocated variables when possible:
int n;
over
int* m = new int; // note pointer
The reason dynamic allocation is prefered in your case is the way the linked list is defined. I.e. each node contains a pointer to a next node (probably). Because the nodes must exist beyond the point where they are created, they are dynamically allocated.
NodeType *N. and traverse my list using this pointer
Yes, you could do that. But note that this is just a pointer declaration. You have to assign it to something meaningful to actually use it.
My question is.. when we just declare a variable, does memory not get assigned right away.. or what's the difference?
Actually, both cases are definitions, not just declarations.
int n;
creates an un-initialized int with automatic storage;
int* n;
creates a pointer to an int. It's dangling, it doesn't point to a valid memory location.
int* n = new int;
creates a pointer and initializes it to a valid memory location containing an uninitialized int.
int* n = new int();
creates a pointer and initializes it to a valid memory location containing a value-initialized int (i.e. 0).
The difference is that automatic storage can only be used when the compiler can determine at compile time how much memory is needed and how long it will be needed for. Typically automatic variables will be allocated on the stack.
Whereas for memory that is allocated dynamically the programmer is responsible for keeping track of this information. This is typically allocated on the heap. Using heap memory will typically have greater overhead for a variety of reasons, and there is a risk of memory leak where you allocate heap memory but never free it.
In the example you described of a linked list, it's unlikely that you know the length of the list at compile time (if you did then you could just use a static array), so that is why you will need to manage the memory explicitly rather than letting the compiler take care of memory management automatically. But the pointer that you use to traverse the list is not needed after the function returns, so that is why it can be managed automatically by the compiler.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With