I am trying to use take realloc a 2D array but I keep getting a Segmentation Fault and it seems to almost positively be stemming from how I am reallocating my 2D array. The array is initially specified to be a size of 3 x 26. My goal is to simple reallocate the first array (3) and just multiply it by 2 while keeping the other arrays all a size of 26.
//Array creation
int ** array_creation (){
int ** arr = (int **) malloc(buffer_size * sizeof(int *));
if(arr==NULL){
cout<<"malloc fail"<<endl;
}
for(int i=0;i<buffer_size;i ){
arr[i] = (int *)malloc(26 * sizeof(int));
if(arr[i]==NULL){
cout<<"malloc fail"<<endl;
}
}
return arr;
}
//Variables
buffer_size = 3;
buffer_count = 0;
if(buffer_count >= buffer_size){
cout<<"Doubling the size of dynamic arrays!"<<endl;
buffer_size = buffer_size * 2;
// arr = (int **) realloc(arr, buffer_size * sizeof(int));
}
So once the buffer_size is equal to the buffer_count I want to just double the first array that would start at 3, so make the 2D array go from 3 array of 26 integers to 6 arrays of 26 integers.
Thank you for any help.
CodePudding user response:
Look at your malloc
int ** arr = (int **) malloc(buffer_size * sizeof(int *));
Now look at your realloc
arr = (int **) realloc(arr, buffer_size * sizeof(int));
See the difference? It should be sizeof(int *)
for both cases.
CodePudding user response:
Correct usage of realloc
(in general) looks as follows; note that you need a temporary variable to hold the result of the reallocation because you'd lose the old pointer on failure otherwise:
auto tmp = realloc(thePointer, newSize);
if(tmp)
{
// cast here or earlier, doesn't matter
thePointer = static_cast<decltype(thePointer)>(tmp);
}
else
{
// appropriate error handling; note how `thePointer` remainded
// unchanged and you still have access to the previous array,
// so you might e.g. free it to avoid memory leaks
}
In your specific case the pointer type is int**
, the new size is buffer_size * sizeof(int*)
(note that you missed an asterisk there in your code!).
However usage of malloc/realloc is discouraged in C . You avoid all this memory management hassle if you use std::vector
instead of raw arrays.