Recently, there is a chance for me to go back through the topic about stack and heap for C++ language.
I think I need keep this experience.
My story is this: some one declared a large array under Linux. No error during compiling but the classic “segment fault” appears once the programing is running.
This often happens under Linux with gcc/g++, not so often on MS Windows. I think it depends on the different memory management strategies.
I try to declare large array, and apply for large memory by new and malloc, then found something interesting:
for my computer environment, the following three programs end up “segment fault”:
declare large array, I try from array[1*] , here ’*’ will be replaced by some number of zeros. This method keeps well until the zeros number comes 8, like the following code:
//main.c
#include <stdio.h>
int main()
{
double array[100000000]// it is 8 zeros,
return 0;
}
using malloc function (the idea is similar with above ), the malloc fails at 10 zeros:
//main.c
#include <stdio.h>
#include <stdlib.h>
int main()
{
double * ptr = (double *) malloc( 10000000000*sizeof(double));
return 0;
}
finally, the new method, it fails on the same condition as the malloc condition:
//main.cpp
#include<stdio.h>
int main()
{
double * ptr = new double[10000000000];
return 0;
}
Now let’s make some conclusion about new, malloc, stack and heap.
Array cannot apply for the memory large as malloc/new, because array declaring creates variable on stack , and new and malloc apply memory from heap. Then array cannot get memory as large as malloc/new did.
In addition: stack address is always continuous, but heap may not. (If confused , come back the Operation System textbook to go through the memory management chapter.) It is the continuous requirement that makes the stack variable, i.e. array could not apply space as large as malloc/new.
Another thing I want to say is that because new will call the constructor, while malloc dose not. Then for some condition or some system, the performance of new and malloc may be different from each other.
(Just for Fun)