-1
#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.

Jeff
  • 3
  • 1

3 Answers3

1

C function arguments are passed by value. This means that when you pass ptr to allocateMem and then modify it within allocateMem, you're not changing anything about ptr.

You are creating a memory leak, since you can't free the memory you've dynamically allocated as you haven't preserved a pointer to it.

Any argument you want a function to modify external to the function you're calling, you need to pass a pointer to, so if you want to modify a pointer, you need to pass a pointer to a pointer, as @babon has demonstrated with the code in their answer.

Chris
  • 26,361
  • 5
  • 21
  • 42
  • "_when you pass `ptr` to `allocateMem` and then modify it within..._" -- To put a finer point on this, `a` is a _copy_ of `ptr`, and it is `a` which is modified, not `ptr`. – ad absurdum Oct 22 '21 at 07:10
0

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.

babon
  • 3,615
  • 2
  • 20
  • 20
0

You can return the pointer to the allocated memory (and check the return value), like this:

#include <stdio.h>
#include <stdlib.h>

int *allocateMem(void)
{
    return (int*)malloc(5 * sizeof(int));
}

int main()
{
    int *ptr;
    if( NULL != (ptr = allocateMem()))
    {
        ptr[0] = 5454;
        ptr[1] = 54;
        printf("Hi %d\n", ptr[1]);
        free(ptr);
    }
    return 0;
}

The constant number 5 in allocateMem should not be hardcoded, or give it a valuable name.

Carlo Banfi
  • 186
  • 1
  • 7