#include <stdio.h>
#include <stdlib.h>
void allocateMem(int *a)
{
a = (int*)malloc(5 * sizeof(int));
}
int main()
{
int *ptr;
allocateMem(ptr);
ptr[0] = 5454;
ptr[1] = 54;
printf("Hi %d\n", ptr[1]);
free(ptr);
return 0;
}
I didn't get any output and error with the code. But if I allocate memory in main function, it actually works.
Here's the fix:
#include <stdio.h>
#include <stdlib.h>
void allocateMem(int **a)
{
*a = malloc(5 * sizeof(int));
}
int main()
{
int *ptr;
allocateMem(&ptr);
ptr[0] = 5454;
ptr[1] = 54;
printf("Hi %d\n", ptr[1]);
free(ptr);
return 0;
}
To write to a variable in another function, you need to pass a pointer to it. Since the intention here is to write to a pointer, you need to pass the address of the pointer - &ptr
.
As an address was passed, the allocateMem()
function dereferences a
once to hop into the memory location which is to be updated and lays down the address returned by malloc()
. When this function returns, main()
finds that ptr
is pointing to a valid address and writes data inside the allocated memory.