I have a problem about malloc(). It is weird. My code is in the following. I use random generator to generate elements for an array. The array is opened by malloc(). If the array size is smaller than 8192, it is OK. If the size is larger than 8192, it shows segment fault.
void random_generator(int num, int * array) {
srand((unsigned)time(0));
int random_integer;
for(int index=0; index< num; index++){
random_integer = (rand()%10000)+1;
*(array+index) = random_integer;
cout << index << endl;
}
}
int main() {
int array_size = 10000;
int *input_array;
input_array = (int*) malloc((array_size));
random_generator(8192, input_array); // if the number is larger than 8192, segment fault
free(input_array);
}
malloc() takes the size in bytes, not the number of elements. The size of an int is typcially 4 bytes, so you are actually allocating only enough memory for 2500 integers. You are allocating array_size bytes, while you should be allocating array_size * sizeof(int) bytes.
So, the error will be fixed by
input_array = (int*) malloc(array_size * sizeof(int));
P.S. Never assume that you know the size of an int or any other data type, as it is platform dependent. Always use sizeof().
P.P.S. This is really a C question, rather than a C++ question. If you are actually using C++, you should consider using new and delete [] instead of malloc() and free(), or better yet use std::vector instead of an array, as Neil pointed out.
You want:
input_array = (int*) malloc( array_size * sizeof(int) );
you might consider the much simpler:
input_array = new int[ array_size ];
// stuff
delete [] input_array;
or even:
std::vector <int> input_array( array_size );
and not have to worry about calling free or delete, or about exceptions.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With