I am trying to create a function that allocates memory of a certain specified size. In the main, I create the pointer and then send the pointer and the size to the function for memory to be allocated. For some reason it causes all sorts of problems. My program works smoothly if I use the malloc in the main, but not through the function.
int main(void){
int * pointer;
int array_size = SIZE;
...
allocate_memory(&pointer,array_size);
...
free(pointer);
}
allocate_memory(int *pointer,int size){
*pointer = (int *)malloc(size*sizeof(int));
if(!(*pointer)){
printf("Memory allocation fail!");
exit(0);
}
The problem now is that it gives me an error when I try to free the memory. I would appreciate it if the solution will come with a short explanation. I am starting to be very confused about how these pointers and castings are working. Thanks in advance!
There were many errors in your program which I am pointing out:
You need to #define the macro SIZE as otherwise the program just won't know what it is.
It's better to declare a prototype of the function allocate_memory() so that any discrepancy in type of arguments or return type is detected
&pointer as an argument to allocate_array() in main().For this it is necessary to define the function as allocate_memory(int **pointer,int size) instead of allocate_memory(int *pointer,int size) which you have done.if(*pointer==NULL) implements the condition in a much simpler way and serves just the same purpose.exit(1) for unsuccessful termination as exit(0) is used to denote successful termination.Here's the corrected code.It compiles well without warnings and does the job (memory allocation) as intended.
#include<stdio.h>
#include<stdlib.h>
#define SIZE 30
void allocate_memory(int**,int);
int main(void){
int * pointer;
int array_size = SIZE;
allocate_memory(&pointer,array_size);
free(pointer);
}
void allocate_memory(int **pointer,int size)
{
*pointer = malloc(size*sizeof(int));
if(*pointer==NULL)
{
printf("Memory allocation fail!");
exit(1);
}
else
printf("\nMemory allocation successful");
}
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