I help teach C in a beginners class. We were covering the use of malloc for dynamic memory allocation and a student wanted to place a wrapper around malloc. I'm not sure if this would ever be useful but playing around with stuff is the best way to learn.
However when the student tried to aplocate memory for an array via their malloc wrapper function it didn't work - Segmentation fault.
A minimum example is given below.
#include <stdlib.h>
void mallocWrapper(int *intArray, int length){
intArray = malloc(length * sizeof(int));
}
int main() {
int *array;
int arraySize = 10;
mallocWrapper(array, arraySize);
// this line causes the Segmentation fault
array[0] = 0;
return 0;
}
As far as I understood the array variable would just become the address of the first point in memory which had been reserved for the array. I assumed this would be the cases regardless of where the memory was allocated i.e. in the main or in mallocWrapper.
As a result I didn't know what to tell the student other than I would get back to them.
Any help would be appreciated. Thanks