C Programming: malloc() inside another function

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

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

提交回复
热议问题