C Programming: malloc() inside another function

后端 未结 9 1197
暖寄归人
暖寄归人 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:04

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

提交回复
热议问题