83

I need help with malloc() inside another function.

I'm passing a pointer and size to the function from my main() and I would like to allocate memory for that pointer dynamically using malloc() from inside that called function, but what I see is that.... the memory, which is getting allocated, is for the pointer declared within my called function and not for the pointer which is inside the main().

How should I pass a pointer to a function and allocate memory for the passed pointer from inside the called function?


I have written the following code and I get the output as shown below.

SOURCE:

int main()
{
   unsigned char *input_image;
   unsigned int bmp_image_size = 262144;

   if(alloc_pixels(input_image, bmp_image_size)==NULL)
     printf("\nPoint2: Memory allocated: %d bytes",_msize(input_image));
   else
     printf("\nPoint3: Memory not allocated");     
   return 0;
}

signed char alloc_pixels(unsigned char *ptr, unsigned int size)
{
    signed char status = NO_ERROR;
    ptr = NULL;

    ptr = (unsigned char*)malloc(size);

    if(ptr== NULL)
    {
        status = ERROR;
        free(ptr);
        printf("\nERROR: Memory allocation did not complete successfully!");
    }

    printf("\nPoint1: Memory allocated: %d bytes",_msize(ptr));

    return status;
}

PROGRAM OUTPUT:

Point1: Memory allocated ptr: 262144 bytes
Point2: Memory allocated input_image: 0 bytes
Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
HaggarTheHorrible
  • 7,083
  • 20
  • 70
  • 81

9 Answers9

113

How should I pass a pointer to a function and allocate memory for the passed pointer from inside the called function?

Ask yourself this: if you had to write a function that had to return an int, how would you do it?

You'd either return it directly:

int foo(void)
{
    return 42;
}

or return it through an output parameter by adding a level of indirection (i.e., using an int* instead of int):

void foo(int* out)
{
    assert(out != NULL);
    *out = 42;
}

So when you're returning a pointer type (T*), it's the same thing: you either return the pointer type directly:

T* foo(void)
{
    T* p = malloc(...);
    return p;
}

or you add one level of indirection:

void foo(T** out)
{
    assert(out != NULL);
    *out = malloc(...);
}
jamesdlin
  • 81,374
  • 13
  • 159
  • 204
  • 1
    I like the assertion; it is a part of the contract for the function which the caller should get systematically correct. Of course, even more subtle code might make a NULL `out` allowable, having it correspond to an optional out-parameter. But that's not what is needed for `alloc_pixels`; the question does not require such sophistication. – Donal Fellows May 15 '10 at 06:56
  • 1
    Is it safe to free(*out) inside the calling function (main in this case)? – William Everett Jan 09 '14 at 16:51
  • 2
    @Pinyaka: It's safe for the caller to call `free()` on the resulting pointer (how else would the caller free the allocated memory?). However, the caller would either be doing `T* out = foo();` (in the first form) or `T* out; foo(&out);` (in the second form). In both cases, the caller would have to call `free(out)`, not `free(*out)`. – jamesdlin Jan 09 '14 at 17:29
92

You need to pass a pointer to a pointer as the parameter to your function.

int main()
{
   unsigned char *input_image;
   unsigned int bmp_image_size = 262144;

   if(alloc_pixels(&input_image, bmp_image_size) == NO_ERROR)
     printf("\nPoint2: Memory allocated: %d bytes",_msize(input_image));
   else
     printf("\nPoint3: Memory not allocated");     
   return 0;
}

signed char alloc_pixels(unsigned char **ptr, unsigned int size) 
{ 
    signed char status = NO_ERROR; 
    *ptr = NULL; 

    *ptr = (unsigned char*)malloc(size); 

    if(*ptr== NULL) 
    {
        status = ERROR; 
        free(*ptr);      /* this line is completely redundant */
        printf("\nERROR: Memory allocation did not complete successfully!"); 
    } 

    printf("\nPoint1: Memory allocated: %d bytes",_msize(*ptr)); 

    return status; 
} 
Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
Mark Ransom
  • 299,747
  • 42
  • 398
  • 622
  • 6
    Why are you calling free in a conditional code block that is guaranteed to have a NULL pointer!?!? The `free(*ptr)` will when called from `main()` try to free `input_image` which was ummm, the term evades me... not dynamically allocated. – James Morris May 14 '10 at 22:45
  • and @James: I did what was suggested by Mark and Matti, but this time both my _mize(input_image) in my main() and _msize(**ptr) in my alloc_pixels(...) function are returning the size as 0. Whereas if it is _msize(*ptr) (single *) returns 262144. ? – HaggarTheHorrible May 14 '10 at 23:09
  • 2
    @James Morris, I just copied the code that was posted in the question and made the minimal number of changes. I didn't want to get caught up in a distraction to the main point. – Mark Ransom May 15 '10 at 01:50
  • @vikramtheone, sorry I was a bit rushed and didn't make this answer as complete as it should have been. I've edited it to be more complete. I hope you can see how it is different than your original code and why it must be this way. – Mark Ransom May 15 '10 at 02:01
  • I tried the same thing on MSVS, but it did not work. input_image remains 'bad pointer'. What could be the reason? – Zeeshan Apr 07 '16 at 09:26
  • @ZeeshanMahmood probably a typo. It's easy to miss the `*` at the beginning of the assignment. – Mark Ransom Apr 07 '16 at 15:43
8

If you want your function to modify the pointer itself, you'll need to pass it as a pointer to a pointer. Here's a simplified example:

void allocate_memory(char **ptr, size_t size) {
    void *memory = malloc(size);
    if (memory == NULL) {
        // ...error handling (btw, there's no need to call free() on a null pointer. It doesn't do anything.)
    }

    *ptr = (char *)memory;
}

int main() {
   char *data;
   allocate_memory(&data, 16);
}
Matti Virkkunen
  • 63,558
  • 9
  • 127
  • 159
  • 1
    It's safe to call `free()` on a null pointer, what is that comment about? – Carl Norum May 14 '10 at 22:37
  • @Carl Norum: It's safe, but pointless. IMO, code that doesn't do anything only leads to confusion for people who end up reading it later and should be avoided. – Matti Virkkunen May 14 '10 at 22:38
  • @Matti Virkkunen: Telling people to not call free on a NULL pointer is pointless *and* misinformation - you're causing people to become confused when they see code that goes against your advice. – James Morris May 14 '10 at 22:43
  • @James Morris: Fine, fine... like the wording better now? – Matti Virkkunen May 14 '10 at 22:49
  • 1
    @Carl: I've encountered (not very nice) C libraries that crashed if asked to `free(NULL);` so it's good to avoid anyway. (No, I don't remember which. It was quite a while ago.) – Donal Fellows May 14 '10 at 22:55
  • @Donal Fellows: Those C libraries are non-conforming, then. The standard requires `free(NULL)` to do nothing. – jamesdlin May 14 '10 at 22:59
  • @Donal Fellows: Sounds like a horribly broken standard library to me... must have really been a while ago – Matti Virkkunen May 14 '10 at 23:03
  • @All here :) I did what was suggested by Mark and Matti, but this time both my _mize(input_image) in my main() and _msize(**ptr) in my alloc_pixels(...) function are returning the size as 0. Whereas if it is _msize(*ptr) (single *) returns 262144. ? – HaggarTheHorrible May 14 '10 at 23:10
  • @vikramtheone: I don't see what the problem is, the return values seem to be correct. – Matti Virkkunen May 14 '10 at 23:18
  • @Matti: How can I find out the size of memory just allocated using the input_image pointer? Why does _msize(input_image) return a 0 and not the size of memory? – HaggarTheHorrible May 14 '10 at 23:33
  • @vikramtheone: Because inside alloc_pixels, ptr is a pointer to the stack of the calling function and not the heap. You need to dereference ptr by doing *ptr to get to the heap address. – Matti Virkkunen May 15 '10 at 00:17
  • @Matti: It was back in the early '90s, and was considered an old std-lib then. Of course, back then we also had all the ridiculous nastiness of `far` pointers, memory models and other things like that, which I'm convinced still leave their mark in standards today (such as in the lack of a guarantee that pointers to data and pointers to functions are the same size). – Donal Fellows May 15 '10 at 06:48
  • In short, life is *much* better now. :-) – Donal Fellows May 15 '10 at 06:49
4

You need to pass the pointer by reference, not by copy, the parameter in the function alloc_pixels requires the ampersand & to pass back out the address of the pointer - that is call by reference in C speak.

main()
{
   unsigned char *input_image;
   unsigned int bmp_image_size = 262144;

   if(alloc_pixels(&input_image, bmp_image_size)==NULL)
     printf("\nPoint2: Memory allocated: %d bytes",_msize(input_image));
   else
     printf("\nPoint3: Memory not allocated");     

}

signed char alloc_pixels(unsigned char **ptr, unsigned int size)
{
    signed char status = NO_ERROR;
    *ptr = NULL;

    *ptr = (unsigned char*)malloc(size);

    if((*ptr) == NULL)
    {
        status = ERROR;
        /* free(ptr);
        printf("\nERROR: Memory allocation did not complete successfully!"); */
    }

    printf("\nPoint1: Memory allocated: %d bytes",_msize(*ptr));

    return status;
}

I have commented out the two lines free(ptr) and "ERROR: ..." within the alloc_pixels function as that is confusing. You do not need to free a pointer if the memory allocation failed.

Edit: After looking at the msdn link supplied by OP, a suggestion, the code sample is the same as earlier in my answer.... but...change the format specifier to %u for the size_t type, in the printf(...) call in main().

main()
{
   unsigned char *input_image;
   unsigned int bmp_image_size = 262144;

   if(alloc_pixels(&input_image, bmp_image_size)==NULL)
     printf("\nPoint2: Memory allocated: %u bytes",_msize(input_image));
   else
     printf("\nPoint3: Memory not allocated");     

}
t0mm13b
  • 34,087
  • 8
  • 78
  • 110
  • I understand what wrong I was doing. There is however one issue still not solved. When I make these changes and use _msize(input_image); in my main(), the _msize(...) returns a 0. At the same time for _msize(*ptr); in the other function, I get the size as 262144. What's going wrong here? I have no clue. – HaggarTheHorrible May 15 '10 at 00:30
  • @vikramtheone: can you show the function prototype for _msize(...) please? Amend your question to highlight that... – t0mm13b May 15 '10 at 09:07
  • Never mind, it works fine now :) It was a late-late night work and my mind had all become fuzzy and I forgot to change the main(). I was not sending the address of input_image when I calling the alloc_memory(...) in main(). – HaggarTheHorrible May 15 '10 at 10:56
3

As mentioned in the other answers, we need a pointer to the pointer. But why?

We need to pass the value by a pointer in order to be able to modify the value. If you want to modify an int, you need to pass it by the int*.

In this question, the value we want to modify is a pointer int* (pointer changed from NULL to the address of the allocated memory), so we need to pass a pointer to the pointer int**.

By doing followed, pInt inside foo(int*) is a copy of the argument. When we allocate memory to the local variable, the one in the main() is intact.

void foo(int* pInt)
{
   pInt = malloc(...);
}
int main()
{
   int* pInt;
   foo(pInt);
   return 0;
}

So we need a pointer to pointer,

void foo(int** pInt)
{
   *pInt = malloc(...);
}
int main()
{
   int* pInt;
   foo(&pInt);
   return 0;
}
Song Wang
  • 290
  • 2
  • 9
2

This does not make sense :

if(alloc_pixels(input_image, bmp_image_size)==NULL) 

alloc_pixels returns a signed char (ERROR or NO_ERROR) and you compare it to NULL (which is supposed to be used for pointers).

If you want input_image to be changed, you need to pass a pointer to it to alloc_pixels. alloc_pixels signature would be the following:

signed char alloc_pixels(unsigned char **ptr, unsigned int size)

You would call it like this:

alloc_pixels(&input_image, bmp_image_size);

And the memory allocation

*ptr = malloc(size);
Bertrand Marron
  • 21,501
  • 8
  • 58
  • 94
1

Parameters' assignment will work only if you set the value to its address.

There are 2 points that you should know before you attempt to solve this problem:
1. C Function: All the parameters you passed to the function will be a copy in the function.

That means every assignment that you've made in the function will not affect the variables outside the function, you're working on the copy actually:

int i = 1;
fun(i);
printf("%d\n", i);
//no matter what kind of changes you've made to i in fun, i's value will be 1

So, if you want to change i in the function, you need to know the difference between the thing and its copy:

The copy shared the value with the thing, but not the address.

And that's their only difference.

So the only way to change i in the function is using the address of i.

For example, there's a new function fun_addr:

void fun_addr(int *i) {
    *i = some_value;
}

In this way, you could change i's value.

  1. malloc:

The key point in the fun_addr function is, you've passed a address to the function. And you could change the value stored in that address.

What will malloc do?

malloc will allocate a new memory space, and return the pointer pointed to that address back.

Look at this instruction:

int *array = (int*) malloc(sizeof(int) * SIZE);

What you are doing is let array's value equals to the address returned by malloc.

See? This is the same question, permanently assigning value to the parameter passed to the function. At this point, the value is address.

Now, assign the address(returned by malloc) to the address(stores the old address).

So the code should be:

void fun_addr_addr(int **p) {
    *p = (int*) malloc(sizeof(int) * SIZE);
}

This one will work.

VELVETDETH
  • 314
  • 1
  • 8
1

In your initial code , when you were passing input_image to the function alloc_pixels, compiler was creating a copy of it (i.e. ptr) and storing the value on the stack. You assign the value returned by malloc to ptr. This value is lost once the function returns to main and the stack unwinds. So, the memory is still allocated on heap but the memory location was never stored in (or assigned to )input_image, hence the issue.

You can change the signature of the function alloc_pixels which would be simpler to understand, and you won't require the additional 'status' variable as well.

unsigned char *alloc_pixels(unsigned int size)
{
    unsigned char *ptr = NULL;
    ptr = (unsigned char *)malloc(size);
    if (ptr != NULL)
       printf("\nPoint1: Memory allocated: %d bytes",_msize(ptr));
    return ptr;
}

You can call the above function in main :

int main()
{
   unsigned char *input_image;
   unsigned int bmp_image_size = 262144;

   if((input_image = alloc_pixels(bmp_image_size))==NULL)
       printf("\nPoint3: Memory not allocated");    
   else
     printf("\nPoint2: Memory allocated: %d bytes",_msize(input_image)); 
   return 0;

}
juventus
  • 52
  • 1
1

The only way I could get pointer to a pointer solution to work for a similar problem I was having for this function

    BOOL OpenBitmap2 ( LPCTSTR pszFileName, char** pszBMPFile)  

Was by assigning a temporary pointer to store the address

    char* BMPFile;
    { BMPFile = (char*)GlobalAlloc(GPTR, dwFileSize + 1);   // allocate storage using GlobalAlloc + 1 for null term string

then reassigning it

    {* pszBMPFile = BMPFile; return (0);} // Error = False

Any comment on why using "* pszBMPFile" directly with GlobalAlloc didn't work would be appreciated. I answered my own question. I forgot to carry the "*" through with pszBMPFile in the other lines of code. Good lessons from all the contributors. Many thanks.

PeterS
  • 11
  • 2