I've always declared my arrays using this method:
bool array[256];
However, I've recently been told to declare my arrays using:
bool* array = new bool[256];
What is the difference and which is better? Honestly, I don't fully understand the second way, so an explanation on that would be helpful too.
bool array[256];
This allocates a bool array with automatic storage duration.
It will be automatically cleaned up when it goes out of scope.
In most implementations this would be allocated on the stack if it's not declared static or global.
Allocations/deallocations on the stack are computationally really cheap compared to the alternative. It also might have some advantages for data-locality but that's not something you usually have to worry about. But you might need to be careful of allocating many large arrays to avoid a stack overflow.
bool* array = new bool[256];
This allocates an array with dynamic storage duration.
You need to clean it up yourself with a call to delete[] later on. If you do not then you will leak memory.
Alternatively (as mentioned by #Fibbles) you can use smart-pointers to express the desired ownership/lifetime requirements. This will leave the responsibility of cleaning up to the smart-pointer class. Which helps a lot with guaranteeing deletion, even in cases of exceptions.
It has the advantage of being able to pass it to outer scopes and other objects without copying (RVO will avoid copying for the first case too in certain cases, but storing it as a data-member and other uses can't be optimized in the first case).
The first is allocation of memory on stack:
// inside main (or function, or non-static member of class) -> stack
int main() {
bool array[256];
}
or maybe as a static memory:
// outside main (and any function, or static member of class) -> static
bool array[256];
int main() {
}
The last is allocation of dynamic memory (in heap):
int main() {
bool* array = new bool[256];
delete[] array; // you should not forget to release memory allocated in heap
}
The advantage of dynamic memory is that it can be created with variable number of elements (not 256, but from some user input for example). But you should release it each time by yourself.
More about stack, static and heap memory and when you should use each is here: Stack, Static, and Heap in C++
The difference is static vs dynamic allocation, as previous answers have indicated. There are reasons for using one over the other. This video by Herb Sutter explains when you should use what. https://www.youtube.com/watch?v=JfmTagWcqoE It is just over 1 1/2 hours.
My preference is to use
bool array[256];
unless there's a reason to do otherwise.
Mike
Related
I am dynamically allocating memory at the beginning of a for using:
Candset_t* emptycandset(void) {
Candset_t* cset;
cset = (Candset_t*)malloc(sizeof(Candset_t));
cset->size = 0;
cset->maxsize = MAXSIZE;
cset->dptr = (Point_t*)malloc(MAXSIZE * sizeof(Point_t));
return cset;
}
whereby Candset and Point_t are both typedef.
later I free the memory at the end of the loop with:
void destroycandset(Candset_t* cset) {
free(cset->dptr);
free(cset);
}
The reason why I am doing this is because I want to reuse the same variable(memory space) in all the iterations of the loop.
This actually cause fragmentation of the heap. Hence, decreased performance. How can I solve this? is it possible to reinitiate a dynamically allocated space? How does this affect the dynamic memory?
Cheers
I am trying to reuse a dynamically allocated memory. However, using malloc and free cause fragmentation of the heap.
Do you know any way to avoid memory fragmentation?
typedef struct point {
double x, y;
unsigned int dst;
} Point_t;
typedef struct candset {
unsigned int size;
unsigned int maxsize;
Point_t* dptr;
} Candset_t;
This is what the struct data look like.
I can't tell what the size of the dptr and Candset_t will be; Hence, I have to allocate them dynamically. It make no difference when using new and delete for c++ only.
For structures smaller than 1 MB whose lifetime is simple, don't use dynamic allocation at all.
Just create a Candset_t in automatic storage (on the stack).
Automatic storage provides memory extremely efficiently.
If your object is "simple" enough to malloc-and-modify, it is also free to create in automatic storage.
There are people who are used to languages like Java or C#, where creating an object is inherently expensive.
In C++, creating an object can be literally free. It can also be expensive. How expensive it is depends on the properties of the object.
Because objects in C++ carry less baggage than in garbage collected languages, the "free" case is really, really free.
To make an object effectively free to use, ensure that it doesn't use dynamically allocated memory at construction time, and to be extra sure avoid virtual functions (sometimes these can also be free). Next, don't use new or malloc to create it.
Here is a simple "free" class:
struct Candset_t {
std::size_t size;
Point_t data[MAXSIZE];
};
so long as MAXSIZE isn't really big, like in the many 1000s, this is going to be a better plan than the original.
If this doesn't work, then you can just move the declaration of Candset_t up a scope, and reuse it. You do not want to reallocate dptr, but instead write code to clear the memory in it.
Generally, calls to malloc or new take 100x or more the time of a typical line of C++ code. So avoid them in tight loops.
I'm trying to use compounds the {} notation of initializer lists for initializing static local constants in C++11.
The question might be a follow-up of one about temporary arrays.
There may be a side track(?) hinting at const (but only for C99?).
Another question brings heap allocation into view, but with a difference,
I think.
The idea is for a function to establish a data structure in its own
scope, once. A static (const) variable definition takes values from the lists as written (by misguided intention: C-style
compound literals). Later, the function should be able to refer to the
structure. The SO links above explain, both directly and indirectly,
why just literals won't work.
Will new help, though?
int undef()
{
static const int vs[3] {1,2,3};
static const int* vss[2] {
vs,
// (const int[3]){1,2,3} // temporary will be lost
new const int[3] {1,2,3}
};
return vss[0][1] + vss[1][1];
}
My guess: new will allocate an array somewhere, initialize the
new array from the temporary {1,2,3} and then that somewhere continues to have an
address. So, nothing is lost. Correct?
Is the above use of new safe and sound, meaning covered by the
standard? C++11 in my case.
This is defined behavior. The only pedantic issue is a technical memory leak. Nothing will ever formally delete it, but it'll only be allocated once, and it'll exist for the entire program's execution. Big deal. The only practical annoyance would be static memory sanitizers reporting a "possible" memory leak, from something like this.
I read about C++ dynamic memory allocation. Here is my code:
#include <iostream>
using namespace std;
int main()
{
int t;
cin>>t;
int a[t];
return 0;
}
What is the difference between the above and the following:
int* a=new(nothrow) int[t];
Use dynamic allocation:
when you need control over when an object is created and destroyed; or
when you need to create a local object that's too big to risk putting on the stack; or
when the size of a local array isn't a constant
To answer your specific question: int a[t]; isn't valid C++, since an array size must be constant. Some compilers allow such variable-length arrays as an extension, borrowed from C; but you shouldn't use them, unless you don't mind being tied to that compiler.
So you'd want dynamic allocation there, either the easy way, managed by RAII:
std::vector<int> a(t);
// use it, let it clean itself up when it goes out of scope
or the hard way, managed by juggling pointers and hoping you don't drop them:
int* a=new int[t];
// use it, hope nothing throws an exception or otherwise leaves the scope
delete [] a; // don't forget to delete it
Your first example is C99-compatible array allocations, which occur on the stack and whose lifetimes are similar to other local variables.
The allocation example is a typical C++ dynamic memory allocation, which occurs from the heap and whose lifetime extends until delete a[] is reached--without this code the memory is "leaked". The one-of-lifetime occurs with the variable is destructed by delete and can occur after the current local scope has ended.
I have a C++ global multidimensional array with static linkage. I am assuming it will be stack allocated (I can't find the relevant section in the standard). Is it allocated contiguously?
Another question:
I want to convert these static global n-dim arrays to be allocated on heap. What is the easiest way considering I want to minimize code changes? I can think of converting the arrays to n-dim pointers and malloc'ing at the start of main and free'ing before exiting main. But I have to worry about the contiguous allocation. Anybody see a better way?
Thanks,
Nilesh.
I have a C++ global multidimensional array with static linkage. I am assuming it will be stack allocated (I can't find the relevant section in the standard).
It will not be on the stack; it will be in the global area. Globals and static-storage objects get their own region of memory that is not part of the heap nor the stack.
Further, stack (the standard calls it "automatic" storage) objects only last as long as the function call they're part of; globals are initialized before main() is called and destroyed after main() exits.
Is it allocated contiguously?
It could be, though I doubt the standard requires it. (Clarification: contiguous storage for a 1-D array is guaranteed, but there's no guarantee there aren't "gaps" between rows in 2-D and up arrays.) If you require contiguous allocation, declare the global array as a one-dimensional vector and use an inline function to convert multiple dimensions to the corresponding index. It's the same as what the compiler would have generated if contiguous storage were guaranteed.
I want to convert these static global n-dim arrays to be allocated on heap. What is the easiest way considering I want to minimize code changes?
Change the global declaration from being an array to a pointer. In this case, vectorizing the storage is strongly recommended. (No, I'm not talking about std::vector, I'm talking about reshaping into a 1-D vector.)
I can think of converting the arrays to n-dim pointers
No such beast. Closes thing is a pointer to an array of pointers, which then point to either vectors or arrays of more pointers, depth determined by number of dimensions. It would be a bear to set up, and also much slower than, the 1-d vector case above with a function to convert N-D coordinates to a 1-D index.
malloc'ing at the start of main and free'ing before exiting main.
This, except you don't have to free at the end unless you're using valgrind or similar to look for memory leaks. The OS frees all your allocations that aren't shared memory upon process exit.
So you get something like:
#include <stddef.h>
static const size_t kDimX = 5;
static const size_t kDimY = 20;
static const size_t kDimZ = 4;
inline size_t DimsToVector(size_t x, size_t y, size_t z)
{
return (x * kDimY + y) * kDimZ + z;
}
float* data = 0;
int main()
{
data = new float[kDimX * kDimY * kDimZ];
// Read elements with: data[DimsToVector(x, y, z)]
// Write v with: data[DimsToVector(x, y, z)] = k;
delete[] data; // Optional.
}
There are fancier ways, probably one in Boost, which define classes and override operator [] to hide some of the ugly, but this is about the minimum to get you going.
It's not allocated on the stack. Global variables are "allocated" in a special memory segment.
As of making your multidimensional array "contiguous", the simplest surefire way I can think of without fighting too much against the type system is to make a typedef of the lower dimension and make a pointer to that type.
typedef int TenIntegers[10];
TenIntegers* ints;
int main()
{
ints = new TenIntegers[50];
// your code here
ints[0][5] = 3;
delete[] ints;
}
1) The memory for globals is allocated somewhere "in memory". It is neither on the stack, nor on the heap. For instance, global constants are usually placed in read-only section of the executable. Strictly speaking, it's implementation dependent. Why do you need to know this?
2) Memory will be continuous.
I have to do an assignment for my class and it says not to use Static arrays, only Dynamic arrays. I've looked in the book and online, but I don't seem to understand.
I thought Static was created at compile time and Dynamic at runtime, but I might be mistaking this with memory allocation.
Can you explain the difference between static array and dynamic array in C++?
Static arrays are created on the stack, and have automatic storage duration: you don't need to manually manage memory, but they get destroyed when the function they're in ends. They necessarily have a fixed size at compile time:
int foo[10];
Arrays created with operator new[] have dynamic storage duration and are stored on the heap (technically the "free store"). They can have any size during runtime, but you need to allocate and free them yourself since they're not part of the stack frame:
int* foo = new int[10];
delete[] foo;
static is a keyword in C and C++, so rather than a general descriptive term, static has very specific meaning when applied to a variable or array. To compound the confusion, it has three distinct meanings within separate contexts. Because of this, a static array may be either fixed or dynamic.
Let me explain:
The first is C++ specific:
A static class member is a value that is not instantiated with the constructor or deleted with the destructor. This means the member has to be initialized and maintained some other way. static member may be pointers initialized to null and then allocated the first time a constructor is called. (Yes, that would be static and dynamic)
Two are inherited from C:
within a function, a static variable is one whose memory location is preserved between function calls. It is static in that it is initialized only once and retains its value between function calls (use of statics makes a function non-reentrant, i.e. not threadsafe)
static variables declared outside of functions are global variables that can only be accessed from within the same module (source code file with any other #include's)
The question (I think) you meant to ask is what the difference between dynamic arrays and fixed or compile-time arrays. That is an easier question, compile-time arrays are determined in advance (when the program is compiled) and are part of a functions stack frame. They are allocated before the main function runs. dynamic arrays are allocated at runtime with the "new" keyword (or the malloc family from C) and their size is not known in advance. dynamic allocations are not automatically cleaned up until the program stops running.
It's important to have clear definitions of what terms mean. Unfortunately there appears to be multiple definitions of what static and dynamic arrays mean.
Static variables are variables defined using static memory allocation. This is a general concept independent of C/C++. In C/C++ we can create static variables with global, file, or local scope like this:
int x[10]; //static array with global scope
static int y[10]; //static array with file scope
foo() {
static int z[10]; //static array with local scope
Automatic variables are usually implemented using stack-based memory allocation. An automatic array can be created in C/C++ like this:
foo() {
int w[10]; //automatic array
What these arrays , x, y, z, and w have in common is that the size for each of them is fixed and is defined at compile time.
One of the reasons that it's important to understand the distinction between an automatic array and a static array is that static storage is usually implemented in the data section (or BSS section) of an object file and the compiler can use absolute addresses to access the arrays which is impossible with stack-based storage.
What's usually meant by a dynamic array is not one that is resizeable but one implemented using dynamic memory allocation with a fixed size determined at run-time. In C++ this is done using the new operator.
foo() {
int *d = new int[n]; //dynamically allocated array with size n
But it's possible to create an automatic array with a fixes size defined at runtime using alloca:
foo() {
int *s = (int*)alloca(n*sizeof(int))
For a true dynamic array one should use something like std::vector in C++ (or a variable length array in C).
What was meant for the assignment in the OP's question? I think it's clear that what was wanted was not a static or automatic array but one that either used dynamic memory allocation using the new operator or a non-fixed sized array using e.g. std::vector.
I think the semantics being used in your class are confusing. What's probably meant by 'static' is simply "constant size", and what's probably meant by "dynamic" is "variable size". In that case then, a constant size array might look like this:
int x[10];
and a "dynamic" one would just be any kind of structure that allows for the underlying storage to be increased or decreased at runtime. Most of the time, the std::vector class from the C++ standard library will suffice. Use it like this:
std::vector<int> x(10); // this starts with 10 elements, but the vector can be resized.
std::vector has operator[] defined, so you can use it with the same semantics as an array.
Static arrays are allocated memory at compile time and the memory is allocated on the stack. Whereas, the dynamic arrays are allocated memory at the runtime and the memory is allocated from heap.
int arr[] = { 1, 3, 4 }; // static integer array.
int* arr = new int[3]; // dynamic integer array.
I think in this context it means it is static in the sense that the size is fixed.
Use std::vector. It has a resize() function.
You could have a pseudo dynamic array where the size is set by the user at runtime, but then is fixed after that.
int size;
cin >> size;
int dynamicArray[size];
Static Array :
Static arrays are allocated memory at compile time.
Size is fixed.
Located in stack memory space.
Eg. : int array[10]; //array of size 10
Dynamic Array :
Memory is allocated at run time.
Size is not fixed.
Located in Heap memory space.
Eg. : int* array = new int[10];
Yes right the static array is created at the compile time where as the dynamic array is created on the run time. Where as the difference as far is concerned with their memory locations the static are located on the stack and the dynamic are created on the heap. Everything which gets located on heap needs the memory management until and unless garbage collector as in the case of .net framework is present otherwise there is a risk of memory leak.
Static array :Efficiency. No dynamic allocation or deallocation is required.
Arrays declared in C, C++ in function including static modifier are static.
Example: static int foo[5];
static array:
The memory allocation is done at the complile time and the memory is allocated in the stack memory
The size of the array is fixed.
dynamic array:
The memory allocation is done at the runtime and the memory is allocated in the heap memory
The size of the array is not fixed.
Let's state this issue with a function
if we have the static array then calling the function() will iterate all the fixed allocated components from the memory. There will be no append.
On the other hand, a dynamic array will extend the memory if we append it.
static arrary meens with giving on elements in side the array
dynamic arrary meens without giving on elements in side the array
example:
char a[10]; //static array
char a[]; //dynamic array