C Programming: malloc() inside another function

后端 未结 9 1070
暖寄归人
暖寄归人 2020-11-22 06:47

I need help with malloc() inside another function.

I\'m passing a pointer and size to the fu

9条回答
  •  南笙
    南笙 (楼主)
    2020-11-22 07:02

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

提交回复
热议问题