I have a void function
void foo(int *ptr) {
//trying to allocate memory to hold 5 ints
ptr = malloc(sizeof(int)*5):
//I loop ptr and assign each with a value i =0 to 4;
}
In the main function I have this lines
int main() {
int *num;
//I called the function
foo(&(num));
free(num);
return 1;
}
I get munmap_chunk() invalid pointer error. I did try to dig in more information, but I could not figure this out. I know it will be basic for those who work in c. I was thinking I am passing by reference and it should work, but it is not. I am new to C, and so far has been a headache.
ptr is a local variable, his lifetime ends with the function, you need a pointer to pointer in order to alter num in main
void foo(int **ptr) {
//trying to allocate memory to hold 5 ints
*ptr = malloc(sizeof(int)*5);
//I look ptr and assign each with a value i =0 to 5;
}
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