C Programming: malloc() inside another function

malloc inside function free outside
malloc array in function
c allocate array inside function
memory functions in c
malloc and free implementation in c
pointer to pointer malloc in c
c malloc string
c malloc array

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

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; 
} 

C Programming: malloc() inside another function, In C, initialization and destruction should be done at the same level of abstraction​. This is important because it defines who is responsible for  The C library function void *malloc(size_t size) allocates the requested memory and returns a pointer to it. Declaration Following is the declaration for malloc() function.

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(...);
}

malloc in main() or malloc in another function: allocating memory for , Using Malloc inside a function %f \n", i, array[i]); } int main() { long i, l = 10; double *array; array = malloc(l * sizeof(double)); createArray(array,  To malloc inside a function, process the code, and then return the pointer to that heap space. To malloc outside of a function, i.e. within main(), and passing that pointer to a void function for processing. My reason for asking is because I want to make my code as easy to understand as possible.

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);
}

Using Malloc inside a function, Home » C Programming Tutorial » The malloc() Function in C In static memory allocation the size of the program is fixed, we can not increase or decrease size while the program is running. So why would Let's face another side of the coin. What is malloc in C? The malloc() function stands for memory allocation. It is a function which is used to allocate a block of memory dynamically. It reserves memory space of specified size and returns the null pointer pointing to the memory location.

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");     

}

The malloc() Function in C, so that it can be used for other purposes. Whenever you pass a parameter to a function, a copy is made, and the function works on that copy. So in your case, you are trying to free a copy of the original object, which doesn't make any sense. You should modify your function to take a pointer, and then you can have it call free directly on that pointer.

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);

C Programming/stdlib.h/malloc, deallocates the old object pointed to by ptr and returns a pointer to a new object that has the size specified by size. The contents of the new object is identical to that of the old object prior to deallocation, up to the lesser of the new and old sizes. The function malloc is used to allocate a certain amount of memory during the execution of a program. The malloc function will request a block of memory from the heap. If the request is granted, the operating system will reserve the requested amount of memory.

Use of realloc(), There are 4 library functions provided by C defined under <stdlib.h> header file to facilitate dynamic memory allocation in C programming. They are: malloc()  Pre-requisite: Dynamic Memory Allocation in C using malloc(), calloc(), free() and realloc() The name malloc and calloc() are library functions that allocate memory dynamically. It means that memory is allocated during runtime(execution of the program) from the heap segment.

What are the difference between malloc() and calloc()?, In this tutorial, you'll learn to dynamically allocate memory in your C program using standard library functions: malloc(),  The malloc() function reserves a block of memory of the specified number of bytes. And, it returns a pointer of void which can be casted into pointers of any form. Syntax of malloc()

Dynamic Memory Allocation in C using malloc(), calloc(), free() and , A common bug in C programming is attempting to access a variable that was Another feature of the stack to keep in mind, is that there is a limit (varies with OS) on the heap, you must use malloc() or calloc() , which are built-in C functions. Nested function is not supported by C because we cannot define a function within another function in C. We can declare a function inside a function, but it’s not a nested function. Because nested functions definitions can not access local variables of the surrounding blocks, they can access only global variables of the containing module. This

Comments
  • <S>Why are you calling free in a conditional code block that is guaranteed to have a NULL pointer!?!?</S> The free(*ptr) will when called from main() try to free input_image which was ummm, the term evades me... not dynamically allocated.
  • 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. ?
  • @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.
  • @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.
  • I tried the same thing on MSVS, but it did not work. input_image remains 'bad pointer'. What could be the reason?
  • Thanks for giving the explanation I was too rushed to provide.
  • +1, I love everything but the assertion, however its fine for such a simple demonstration.
  • 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.
  • Is it safe to free(*out) inside the calling function (main in this case)?
  • @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).
  • It's safe to call free() on a null pointer, what is that comment about?