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!
Answer
There were many errors in your program which I am pointing out:
You need to
#define
the macroSIZE
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- You had passed
&pointer
as an argument toallocate_array()
inmain()
.For this it is necessary to define the function asallocate_memory(int **pointer,int size)
instead ofallocate_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.- Use
exit(1)
for unsuccessful termination asexit(0)
is used to denote successful termination. - Never ignore warnings.It's not a good practice.
Here's the corrected code.It compiles well without warnings and does the job (memory allocation) as intended.
#include
#include
#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");
}
No comments:
Post a Comment