c++ malloc segmentation fault -
i have problem malloc(). weird. code in following. use random generator generate elements array. array opened malloc(). if array size smaller 8192, ok. if size larger 8192, 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 number larger 8192, segment fault free(input_array); }
malloc()
takes size in bytes, not number of elements. size of int
typcially 4 bytes, allocating enough memory 2500 integers. allocating array_size
bytes, while should allocating array_size * sizeof(int)
bytes.
so, error fixed
input_array = (int*) malloc(array_size * sizeof(int));
p.s. never assume know size of int
or other data type, platform dependent. use sizeof()
.
p.p.s. c question, rather c++ question. if using c++, should consider using new
, delete []
instead of malloc()
, free()
, or better yet use std::vector
instead of array, neil pointed out.
Comments
Post a Comment