Unlike Java, C++ arrays can be allocated on the stack. Java arrays are a special type of object, hence they can only be dynamically allocated via "new" and therefore allocated on the heap.
Creating an array in the heapallocates a new array of 25 ints and stores a pointer to the first one into variable A. double* B = new double[n]; allocates an array of 50 doubles. To allocate an array, use square brackets around the size.
Stack memory allocation is considered safer as compared to heap memory allocation because the data stored can only be access by owner thread. Memory allocation and de-allocation is faster as compared to Heap-memory allocation. Stack-memory has less storage space as compared to Heap-memory.
If the programmer uses large structures or size arrays, they would be better off using the heap as you can allocate a large size to it. If the programmer just needs tiny variables that only need the quick ins and outs, then utilizing the stack would be the better choice.
I guarantee that this question has been asked before, but I haven't been able to find it via search; sorry in advance for any redundancies.
It's my (potentially wrong) understanding that you only allocate to the stack when you know the size of an object at compile time. So in the case of initializing an array, you could do one of these (and this should go on the stack):
char charArray[50];
Since the size of this array is known at compile time, this should have no issues.
On the other hand, this (I believe) is also valid code:
char anotherCharArray[someVariable + 50];
Would this go on the stack as well? I am pretty sure the code segfaults if you free() this, so it makes me think it does, but it doesn't really make sense to me. Similarly, is the 100% sole situation where you have to use free() when the data was allocated via malloc?
Thanks in advance for your help.
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