Array in C and malloc
1.How the two dimension stored in the memory, are they consecutive? (I mean the int[M][N], not the dynamic allocation, I think the int[M][N] happened in the stack area, so continual, isn't it?)
2.Does the area allocated by malloc must is consecutive?
3.If there is no need to dynamic allocate memory space, where should I use? stack or heap. For example, I want a char array to store 10000 chars, so should I use:
char a[10000];
or
char *a = calloc(sizeof(char),10000);
Is the "function call stack" in the same area as the variable stack??In the same stack or different?
In int numbers[m][n]
the n's are consecutive ints in memory, eg numbers[0][0]
is followed by numbers[0][1]
.
On the other hand, lets say n=10, then numbers[m][9]
is followed by numbers[m+1][0]
.
malloc
returns consecutive memory. you decide how to use it.
A 10000 byte array on the stack is no problem unless the function is recursive and (as Carey notes) unless you are developing in a small stack environment ie. embedded.
Yes the callstack and local variables are identical.
The memory is contiguous. All items in one dimension will be consecutive followed by the next dimension.
Yes. All memory allocated by a single call to malloc()
is contiguous.
If you need a lot of memory, I recommend allocating it dynamically. For less memory, you could allocate statically. malloc()
does use the heap. I don't recommend the stack except for only very small amounts of memory.
When you allocate something[a][b] is it contiguous?
Yes
When I made games that had tiled maps I would even access a tile using a pointer in rendering.
Ie: if the map was 10x10, I would render tile [1][3] by using arrayName[14]
for example.
Also keep in mind using that fact, that in some places, [b] instead of [a] is what will be completely on the memory, this might cause bugs if you are relying on code that came from FORTRAN (like CBLAS) or in some specific devices and situations (like some GPU with some particular drivers).
When you use malloc, it must be contiguous?
Yes, and it will fail if contiguous memory is not available. It is a very common mistake to expect that a program will work because the total free memory exists, without taking in account memory fragmentation.
I made once a game that failed to work because it had 30mb of memory but could not load a 16mb image... I did not realised at the time that memory fragmentation caused by my code was making no block of 16mb be available.
If there are no need for dynamic allocation, I should use stack or heap?
In C, dynamic allocation usually means heap allocation anyway, early C books even explicitly say that malloc
and similar family of functions ( calloc
included) operate only on the heap. while automatic allocation attempts to use the stack.
上一篇: malloc像使用自定义堆的函数
下一篇: C和malloc中的数组