title: C Programming: malloc() inside another function
body: <p>I need help with <code>malloc()</code> <strong><em>inside another function</em></strong>.</p>
  
  <p>I'm passing a <strong>pointer</strong> and <strong>size</strong> to the function from my <code>main()</code> and I would like to allocate memory for that pointer dynamically using <code>malloc()</code> 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 <code>main()</code>.</p>
  
  <p>How should I pass a pointer to a function and allocate memory for the passed pointer <strong>from inside the called function</strong>?</p>
  
  <hr>
  
  <p>I have written the following code and I get the output as shown below.</p>
  
  <p><strong>SOURCE:</strong></p>
  
  <pre><code>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;
  }
  </code></pre>
  
  <h2>PROGRAM OUTPUT:</h2>
  
  <pre><code>Point1: Memory allocated ptr: 262144 bytes
  Point2: Memory allocated input_image: 0 bytes
  </code></pre>