Wednesday, 5 October 2016

c - malloc not allocating properly with pointer to pointer



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:




  1. You need to #define the macro SIZE as otherwise the program just won't know what it is.



  2. 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


  3. You had passed &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.

  4. if(*pointer==NULL) implements the condition in a much simpler way and serves just the same purpose.

  5. Use exit(1) for unsuccessful termination as exit(0) is used to denote successful termination.

  6. 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

c++ - Does curly brackets matter for empty constructor?

Those brackets declare an empty, inline constructor. In that case, with them, the constructor does exist, it merely does nothing more than t...