C/C++ Dynamic or Static memory allocation? - c++

Dynamic memory allocation in C/C++ happens through malloc and the static memory allocation ex: int a[3]; its allocated after the code is executed.
But this code int x[y+1]; only can happen after a value is attributed to y and this happens in execution time, so its static, dynamic or both? does the compiler insert a malloc in the machine code automatically?

It is a Variable Length Array (VLA). Wikipedia: http://en.wikipedia.org/wiki/Variable-length_array
Technically, it is not legal in C++, but compilers often support it as an extension, but generate warnings when they are turned on. See
Why aren't variable-length arrays part of the C++ standard?
It is legal in C.

int[] is on the stack, while malloc'd or new'd things are on the heap.
VERY basically int[] gets allocated automatically when it is reached (where y is already known) and gets dropped when it gets out of scope. It is not everything already allocated at startup.
There are no hidden malloc calls or stuff, that is just how the stack memory works.
(I hope for an answer from someone who actually knows C/C++)

Related

Does char* with text automatically reserves memory as if malloc is used?

// Example program
#include <iostream>
#include <string>
using namespace std;
int main()
{
char **p;
p = (char **)malloc(100);
p[0] = (char *)"Apple"; // or write *p, points to location of 'A'
p[1] = (char *)"Banana"; // or write *(p+1), points to location of 'B'
cout << *p << endl; //Prints the first pointer
}
In the above code :
p[0] = (char *)"Apple";
seems to reserve memory automatically. There is no malloc. Is this C/C++ standard or compiler specific?
UPDATE 1
I am actually interested how it is in C and then in C++. It is just that I did not have a C compiler installed for the code above, so I used C++.
So p is allocated on the STACK pointing to a block of memory (array) in the HEAP where each element points (is a pointer) to a literal in the DATA segment? Wow!
seems to reserve memory automatically. There is no malloc.
Dynamic allocation is not the only way to acquire memory in C++.
The variable p has automatic storage. The string literals are arrays that have static storage. Objects with automatic, static or thread local storage are destroyed automatically. All variables have one of these three storage durations.
Automatic objects are destroyed at the end of the (narrowest surrounding) scope, static objects are destroyed after main returns and thread local objects are destroyed when the thread exits.
Is this C/C++ standard or compiler specific?
The example program is mostly standard, except:
You haven't included a header that is guaranteed to declare malloc.
You haven't created char* objects into the dynamically allocated memory, so the behaviour of the program is technically undefined in C++. See P.P.P.S. below for how to fix this.
P.S. It is quite unsafe to point at string literals with non-const pointers to char. Attempting to modify the literal through such pointer would be syntactically correct, but the behaviour of the program would be undefined at runtime. Use const char* instead. Conveniently, you can get rid of some of the explicit conversions.
P.P.S. C-style explicit conversions are not recommended in C++. Use static_cast, const_cast or reinterpret_cast or their combination instead.
P.P.P.S. It is not recommended to use malloc in C++. Use new or new[] instead... or even better, see next point.
P.P.P.P.S. It is not recommended to have bare owning pointers to dynamic memory. Using a RAII container such as std::vector here would be a good idea.
P.P.P.P.P.S. Your example program leaks the dynamic allocation. This is one of the reasons to avoid bare owning pointers.
So p is allocated on the STACK pointing to a block of memory (array) in the HEAP where each element points (is a pointer) to a literal in the DATA segment?
The language itself is agnostic to concepts such as stack and heap memory and data segment. These are details specific to the implementation of the language on the system that you are using.
malloc does dynamic memory allocation. Here you have classic static memory allocation, where string constants will be allocated in data section of your binary (if I'm not mistaken). Compiler knows in advance how many bytes you need, so it will just allocate it during compilation. This is as opposed to malloc, where you can ask for any number of bytes calculated in runtime and unknown in advance.
Same with arrays that you declare with constant length, without using malloc.
[This is the C answer, since the question was originally tagged [c] also. But it mostly applies to C++ as well.]
When you say
char *str = "text"
or, as in your code,
p[0] = "Apple";
the compiler does allocate memory for those strings "test" and "Apple". It definitely is not as if malloc was called, however. In particular, the memory where those strings are stored is not guaranteed to be (and, these days, typically is not) writable. And you can't pass those pointers to free or realloc -- because, again, they did not come from malloc in the first place.
This is a longstanding aspect of C (and, by extension, C++), true since forever and under any compiler.

dynamic array declaration in c++

I have seen two ways to declare a dynamic array in C++. One is by the use of new operator:
int *arr = new int [size];
and other is directly declaring:
int arr[size];
NOTE: Here note that size is a variable whose value will be provided by the user at runtime.
Question is what is the best approach to declare a dynamic array in C++?
Assuming your question is, "what is better?".
The second, the direct creation of the array, creates the array on the stack, the first on the heap. The second is called variadic-length-array (VLA), which is nonstandard C++ and not portable, but in C it is standard. The GNU C++ compilers support that, but others do not support that. Internally the array is allocated as with alloca(POSIX)/__builtin_alloca(GNU), which extends the stackframe. The variadic-length-array can smash your stack with a big size (maybe produces a SIGSEGV, but may also corrupt other data), while the new-operator throws a catchable exception. (However, using recursive functions can smash your stack the same way...). It is not a bad practice to use VLAs, when you know the size is relatively small. The VLAs can even improve the performance, when the array needs to be allocated multiple times (the allocation of the VLA is faster than the allocation on the heap). Because of the VLA living on the stack it doesn't need to be freed/deleted, it is automaticly freed when the function quits.
This applies to the GNU-Compilers: VLAs do call the destructors on destruction, but the memory allocated with alloca/__builtin_alloca is just going to be freed at the end of the function as memory (allocated with malloc) freed with free.
As conclusion, I think the allocation with the new is better for most problems. But the VLA is good for fast memory allocation local in a function. There is no portable approach to return a VLA from a function (without hacking through assembly) (You can return arrays with constant size from a function, however it needs to be specified in the signature). For this, there is std::array and std::vector, I recommend to use that instead of hand made memory management (the allocation with new and delete or Cs malloc and free), which is not freed when an exception is raised. Memory-management should always be nested in the constructor and destructor of a class, if you need to use such functions. The destructors are always called, when the object goes out of scope, so there are no memory leaks.
One thing you cannot do with VLAs and new/delete is fast resizing. Even std::vector does not use it. It is done with the C-function realloc, which tries to keep the buffer inplace. When you need this you can easily design a std::vector-like class, which should call free in the destructor. To destruct an element you call element.~T(), where T is the type of element.
However std::vector tries to improve the performance of resizing by allocating a buffer with additional space.
The main difference between the two methods is that the first allocates memory from the Free-store(Heap), the second one allocates from the stack. In fact the second one is not good to use because the stack memory is very limited in space compared to the heap. Also the first statement obviously returns a pointer to the first element in the allocated memory while the second one returns the array itself.

At which memory segment the new () operator allocates memory for prgrammer when used [duplicate]

This question already has answers here:
C++, Free-Store vs Heap
(7 answers)
Closed 4 years ago.
For example when we write:
int * p = new int[5];
at which memory segment the memory will be allocated?
In C I know that when we use malloc() it allocates memory in heap section but for C++ I am not sure. I read that, for new() memory allocated from free store and for malloc() memory allocated from heap on this link.
What is this free store? Is it part of RAM only? Is there any diagram for memory management containing free-store like we have for C?
What you're missing is that C++ does not describe, nor does it attempt to describe, these physical machine specifics. C++ is an abstraction. C++ source code doesn't list a sequence of steps to be performed by a computer: it describes the meaning of a program. Similarly, the language does not (generally) mandate such implementation specifics as a "heap".
When it says "free store", the language standard refers to the conceptual area of storage where dynamically allocated objects go. With your compiler, on your computer, in this decade, that may be a "heap" like structure in memory that you are familiar with. Or, it may be somewhere else. Ours is not to reason where.
Ultimately, the text on that website you linked to ("In case of new, memory is allocated from free store where as in malloc() memory allocation is done from heap") is simply wrong, and this is why you should not learn C++ from random websites.
The C++ standard doesn't specify.
All it states is that p has dynamic storage duration.
Practically you'll probably find that it is on the "heap" (which is an implementation concept not a language concept), much in the same way as the sister function malloc of C allocates memory on the "heap".
The free store is one of the two dynamic memory areas, allocated/freed by new/delete. Object lifetime can be less than the time the storage is allocated; that is, free store objects can have memory allocated without being immediately initialized, and can be destroyed without the memory being immediately reallocated.
Click here for details

C++ memory allocation in arrays

int m,n;
cin>>m>>n;
int A[m][n];
Question is: Will array A get memory on stack or heap in C++ ?
Edit: I know using new is a better route.
This technique works in my mingw g++ compiler. I am just curious.
This behaviour depends on the particular compiler and is not part of the standard.
In gcc, which mingw is a port of, the memory for automatic variables as such, including variable lengths arrays is allocated on the stack.
According to the gcc manual:
6.19 Arrays of Variable Length
[...] These arrays are declared like any other automatic arrays, but with a
length that is not a constant expression. The storage is allocated at
the point of declaration and deallocated when the block scope
containing the declaration exits. [...] You can use the function alloca to get an effect much like variable-length arrays.
Ref: https://gcc.gnu.org/onlinedocs/gcc/Variable-Length.html
According to man 3 alloca:
The space allocated by alloca() is allocated within the stack frame
Please keep in mind that:
ISO C++ forbids variable length arrays
Alternatively you can allocate your array dynamically (with new) or preferably use the C++ containers anyway where possible.
Edit: Added note on variable behaviour between compilers, based on Paul's comment.

Is it possible to deallocate a statically defined array?

Can you release the memory of an array defined with static allocation?
No, it is not possible to de-allocate statically allocated memory.
Depending on the language (for example C/C++, using pointers) you may be able to use the memory held by this array for other purposes, but doing so will only re-use the memory; memory won't be released per-se.
This said, this idea of reusing static memory for / with variables other than the variables originally defined there, is only suggested to help understand the nature of this type of allocation. In practical terms, and in particular as a novice, it makes absolutely no sense to have the need for such a feature:
either the variable is expected to have a lifetime as long as the program
at which case it should be declared static
or the variable is not going to be needed at some time during program execution
at which case it should be dynamically allocated (? shortly after/during program initialization) and released whenever appropriate.
No, static allocation means it's automatically allocated at the start of the program, and lives for the entire duration of the program, and then is automatically released at termination.
In short... no.
Think of this memory as being "application scoped" and thus allocated/deallocated following the life-cycle of the application.
this is possible.
static arrays are deallocated automatically before process finishes.
no... its not possible but if you assign that array pointer to other pointer it will cause memory leak..