As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance.
Closed 11 years ago.
What is the difference between:
int myArray[5];
and
int* myArray = new int[5];
int myArray[5] is a bunch of five integers with automatic (or static) storage duration (local memory, often classified as "in stack"). Local memory gets cleared in C++ when the specific scope is exited.
int* myArray = new int[5] is a bunch of five integers on with dynamic storage duration (dynamic memory, often classified as "in heap"). Dynamic memory won't get cleared when the specific scope is exited (myArray has to be an int pointer to store the location of your dynamically created memory).
View the following example:
void foo(){
int myArray[5];
}
void bar(){
int* myArray_dynamic = new int[5];
}
int main(){
foo();
bar();
}
foo will use stack memory, so when foo returns/exits the memory will get freed automatically. However, the dynamic allocated memory, which location is stored in myArray_dynamic in bar won't get freed, as the compiler will only free the memory of myArray_dynamic, not the memory that's stored at its value.
This will create a memory leak, so for every use of new or new[] there has to be a call of delete or delete[] (except you are working with smart pointers, but that's for another question).
The correct version of bar is
void bar(){
int* myArray_dynamic = new int[5];
delete[] myArray_dynamic;
}
The primary reason to pick one or the other is that dynamic allocation is slower, but can be any size (automatic arrays must have a fixed compile-time size), and also that space on the stack is limited, and if you run out, very bad things happen.
The first is an array that's a block of memory allocated either statically or as an automatic variable on the stack during the execution of a function ... it really depends on the context in which its declared/defined.
The second won't compile :-)
To be serious, you really want:
int* myArray = new int[5];
which means we've declared a pointer-type variable that points to an array of integers, and the array of integers is allocated dynamically by the C++ runtime on the heap by the call to new, which is a segment of memory allocated by the OS for your process to dynamically allocate variables in.
The difference is the lifetime.
int myArray[5];
This reserves storage for an array 5 of int. If myArray is declared at block scope, the array is discarded at the end of the block where it is declared.
int* myArray = new int[5];
This dynamically allocates an array 5 of int, the array exists until it is freed with delete [].
What is the difference
One is valid.
The other is not.
In the second you must write
int* myArray = new int[5];
new retuns pointer to the area dynamically allocated in heap.
Related
This question already has answers here:
Must I delete a static array in C++?
(4 answers)
A bit confused on exact meaning of dynamic memory allocation for C++
(2 answers)
Closed 7 years ago.
Why it has error in releasing the static array in debug mode?
int main()
{
int ar[] = { 1,2,3,4,5,6,7,8,9 };
//other code
delete(ar);
// or free(ar);
return 0;
}
I used free or delete to release the array and it finished with error in debug mode.
Do i use the free or delete correctly?
How can i release the array?
ar[] is not allocated on the heap, but local/on the stack, so can't be (and shouldn't be) deleted.
The memory is released on function (or block {}) exit.
You can only use delete with new or free() with malloc()
the delete operator and 'free' function are to be used only on pointers that
own memory allocated on the heap. your array is allocated on the stack, and
the internal implementation will crash when it will not find any heap structure.
moreover, delete is only to be applied on memory allocated with new
and free only on memory allocated with malloc,calloc or realloc.
last thing is that when you use delete on an array, use delete [] for
this means that the removal will take place on an earlier offset on the stack,
when the record of the array itself is allocated, doing otherwise might end with a memory leak or worse
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
dynamic memory allocation by pointers
what is the link between pointers and dynamic memory allocation . why do we use pointers for
dynamic memory allocation . whenever we use new operator we use only pointer variables why?
can anyone explain with an example
According to your question to start with you need not programming but real life example.
Imagine you live in your ordinary flat, it has its own address and on the door you can see big sign "Robin Mandela". It's like static memory allocation. On the start of your program you have some room in memory and a name associated with it. On every vacation you fly to other country where you rent a room in a hotel. You can live one year in one room, another year in another room and even change room during your vacation. You may even not really be interested in what room exactly you will live in, but you need to know that you precisely will have one to live in.
When you ask for dynamic memory allocation, you get some portion of memory. This memory can be allocated almost anywhere, like a room in hotel, and of course you need a key with number to know where to find it. A pointer is like that number on the key - it grants you access to your allocated data.
Also one year you may decide not to go on vacation and rent a room at all. You can't do this with your flat - you have just got it, live there or not. It's like static memory in program.
The size and location (memory address) of objects of automatic and static storage duration is known at compile time. The objects can be accessed through variables and the compiler handles the memory implicitly.
Dynamic memory on the other hand, is allocated at run time, as the name implies. Because it happens at runtime, the compiler can not have knowledge of where the memory is allocated and therefore can not handle the memory for the you. You must access the memory using it's address.
How to get the address of dynamically allocated memory?
It is returned by the new operator which allocates the memory and constructs the object. Since using dynamic memory just in one statement is not useful, you must store the address in a variable.
What type of variable can store a memory address of an object?
A pointer type. The type of the return value of a new-expression is a pointer to the type of object you constructed.
An example:
void foo() {
Foo f; // The object of type Foo has automatic storage and can be accessed through the variable `f`.
Foo* f_ptr; // The pointer object has automatic storage and is not yet initialized.
new Foo; // Bad! The dynamically allocated memory can not be accessed in any way (it has leaked).
f_ptr = new Foo; // The address of another dynamically allocated object is assigned to the f_ptr variable. The object is accessible through this pointer.
delete f_ptr; // Dynamically allocated objects must be deleted explicitly.
// f and f_ptr are destroyed automatically when the scope ends. If the memory pointed by f_ptr was not deleted before this, the memory would leak.
}
The question itself is a bit nonsensical. The keyword new is for allocating memory on the heap and returns either a pointer to the allocated object or throws a std::bad_alloc if allocation fails. It's in a sense like asking why int main(int argc, char** argv) returns an int.
In C++ you have two address spaces to work with; the stack and the heap.
Generally you want to use the heap for allocating your objects and pass them to functions either by reference, the preferred way, or by pointer. In some cases you can't use the stack, mainly when you either don't know how long the object you are creating is going to be alive or when you know that the object should live longer than the scope that creates it. For those cases you should be using std::unique_ptr or std::shared_ptr if you are using C++11 since the object will be deleted automatically when it's no longer needed.
Use of the keyword new is generally discouraged and should only be used when you're certain that neither of the above works.
To read up on the operator new:
cppreference.com
wikipedia
shared_ptr:
cppreference.com
Difference between stack and heap:
learncpp.com
The function you use (for example: malloc() in c) try to get a part of the memory with the length you asked and then it gives you the address of this part of the memory if the allocation was successful else it gives you a 0 (in c and c++ at least).
(When you want to have memory for an array of n items, you must ask for n * item size and you will get the address of the array which is also the address of the first element of your array in fact.)
Example: I want an array of 10 integers
// ask for allocation and get the address of the memory
int * my_array = (int *)malloc(10*sizeof(int));
// you must verify that the allocation was successful
if(my_array != 0) {
// the system gave you the memory you need
// you can do your operations
// " * my_array " and " my_array[0] " have the same meaning
my_array[0] = 22;
* my_array = 22;
// This two lines make the same thing : the put 22 in the memory at the adresse my_array
// same thing for " *(my_array + 9*sizeof(int)) " and " my_array[9] "
my_array[9] = 50;
*(my_array + 9*sizeof(int)) = 50;
// This two lines make the same thing : the put 50 in the memory at the adresse my_array + 36
// 36 = 9*4 (sizeof(int) = 4 in most cases)
free(my_array); //always free the memory to give back the memory to the system and do not "lost it"
}
It is the same in c++ but you replace malloc by new and free by delete. They are keyword but you can see them as functions to understand what it is done.
This question already has answers here:
Dynamically allocating an array of objects
(7 answers)
Closed 8 years ago.
Im learning at the moment c++ with a book.
I have many problems with the pointers...
int i;
cin >> i;
const int *quantity = &i;
int array[*quantity];
Is that correct? Can i control now the size of the array during the programm is running?
That's very nearly correct, except that the size of the array (which you've attempted to allocate on the stack here) has to be known at compile time, so no you can't do this.
However, you can allocate an array at runtime using new[], which will let you pass in a size that's not a compile time constant (new allocates on the heap):
int* array = new int[*quantity];
// ...
delete[] array; // Manual allocations with `new` require manual deallocations
Note that in your particular code example, there's no need to play with pointers at all -- you can just use i directly:
int* array = new int[i];
No, this is incorrect. Array size must be a constant expression, which means that it can be evaluated during compilation, and this is not the case for your code.
If you want arrays of different sizes, you can use dynamic allocation:
int* array = new int[i];
Or much better use std::vector:
std::vector<int> array(i);
Arrays are a fixed size in memory. Because arrays also represent a contiguous block of objects in memory, by definition the same array cannot change size in memory, because it would then need to move memory that may not even belong to the same application.
There are ways to move your array, however, copying it to a new array with more space when it gets full, and there are more mutable types such as std::Vector, but an array as deifned here cannot ever change size.
What this code would instead do is
place a value in i
Place a value in quantity representing the address (pointer) of i
Create a new array using the value in the address quantity
Note that pointers are addresses, specifically saying the byte address in RAM of a given variable (try printing a pointer directly, for example!). The * and & operators quickly say "get value at address" and "get address of"
As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance.
Closed 9 years ago.
When should I use the new-operator?
In my example I get the same result using two different methods:
#include <iostream>
int main() {
int *p1;
int n1 = 5;
p1 = &n1;
int *p2;
p2 = new int;
*p2 = 5;
std::cout << *p1 << std::endl;
std::cout << *p2 << std::endl;
return 0;
}
The purpose of using dynamically allocated memory is one (or many) of the following
Run-time control over object's lifetime. E.g. the object is created manually by new and destroyed manually by delete at user's desire.
Run-time control over object's type. E.g. you can deside the actual type of polymorphic object at run-time.
Run-time control over objects' quantity. E.g. you can decide the array size or the number of elements in the list at run-time.
When the object is simply too big to be reasonably placed into any other kind of memory. E.g. a large input-output buffer that is too big to be allocated on stack
In your specific example none of these reasons apply, which means that there's simply no point in using dynamic memory there.
Considering recent C++11 and upcoming C++14 standarts, you should mostly use new operator while programming in languages with garbage collection, such a Java or C#. It is quite natural for these languages. But in modern C++ you can (and mostly always should) avoid allocating memory directly. We have a nice set of smart pointers instead now.
Use new when you want to allocate from the heap, not the stack. Or moving up a level of abstraction. Use new when you need the allocated memory to remain allocated after you the function (more properly scope) in which it is allocated may (in the case of threading) have exited.
You should use new when you wish an object to remain in existence until you delete it. If you do not use new then the object will be destroyed when it goes out of scope.
Some people will say that the use of new decides whether your object is on the heap or the stack, but that is only true of variables declared within functions.
Allocating (and freeing) objects with the use of 'new' is far more expensive than if they are allocated in-place so its use should be restricted to where necessary.
int * p2 = new int;
The new int part tells the program you want some new storage suitable for holding an
operator uses the type to figure out how many bytes are needed.
Then it finds the memory and returns the address. Next, you assign the address to p2, which is
declared to be of type pointer-to-int. Now p2 is the address and *p2 is the value stored
there. Compare this with assigning the address of a variable to a pointer:
int n1;
int * p1 = &n1;
In both cases (p1 and p2), you assign the address of an int to a pointer. In the second
case, you can also access the int by name: p1. In the first case, your only access is via the pointer.
Remember that you should use delete for freeing the memory allocated by new
delete p2;
You need to read some good books ...
I think that "C++ Primer plus" is a good one for you
In this piece of your code you do deal with memory, but with automatic memory. The compiler sorts out for you where to store each variable. you have p1 pointing at n1 but most work was done automatically.
int *p1;
int n1 = 5;
p1 = &n1;ou
However in the next piece of code you request to dynamically allocate an int
int *p2;
p2 = new int;
*p2 = 5;
here you have created a new integer that has been stored dynamically, therefore you should also delete it otherwise you have created your first memory leak. If you allocate dynamically you have to take care you delete it after use.
delete p2;
This is the largest diference when you start to allocate memory using new do delete it otherwise the deconstrucor of an instance of an object will not run and therefore not clear the memory you have allocated.
As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance.
Closed 12 years ago.
I've always done allocations dynamically on the heap; I've done a lot of Objective-C programming as well as plain C and since I'm usually dealing with large chunks of memory, heap objects are necessary to prevent a stack overflow.
I've recently been told that using dynamically allocated objects is discouraged in C++ and that stack objects should be used whenever possible. Why is this?
I guess the best way to illustrate this is by example:
Class *_obj1;
Class *_obj2;
void doThis(Class *obj) {}
void create() {
Class *obj1 = new Class();
Class obj2;
doThis(obj1);
doThis(&obj2);
_obj1 = obj1;
_obj2 = &obj2;
}
int main (int argc, const char * argv[]) {
create();
_obj1->doSomething();
_obj2->doSomething();
return 0;
}
This creates 2 objects, stores them in the pointers, then main() calls a method on each. The Class object creates a char* and stores the C string "Hello!" in it; the ~Class() deallocator frees the memory. The doSomething() method prints out "buff: %s" using printf(). Simple enough. Now let's run it:
Dealloc
Buff: Hello!
Buff: ¯ø_ˇ
Whoa, what happened? C++ deallocated that _obj2 even though we stored a pointer to it; that's because it's on the stack and not the heap, and C++ has no retain count mechanism like Objective-C (I tried implementing one at one point; it worked perfectly but I didn't feel like adding it to everything as a superclass). So we have to jump through hoops to keep it around after the function returns.
Instead of objects, think of "simpler" types. Would you do this:
void create() {
int *obj1 = new int();
int obj2;
_obj1 = obj1;
_obj2 = &obj2;
}
Would you think this would work? Clearly not.
It's very simple. You can't pass out the pointer to an object allocated to the stack (and, as a rule of thumb, you shouldn't pass out the pointer to an object you have just allocated. If someone allocates an object he is responsable to free it)
Heap objects per se are not wrong, failure to manage their lifetime is.
Stack objects have the property that their destructor will be called regardless of how the code leaves the function (exception, return value). Smart pointers exploit this to manage the lifetime of heap allocated objects (a happy medium?)
A basic design principle of C++ is that you don't pay for what you don't use, so that C++ can be used to write highly optimized code. Stack allocation is more efficient, whatever your language.