C 编程 : malloc() inside another function

标签 c function pointers malloc

我需要有关 malloc() 在另一个函数中 的帮助。

我将一个指针大小从我的main()传递给函数,我想为那个指针分配内存从被调用函数内部动态使用 malloc(),但我看到的是......正在分配的内存用于在我的被调用函数中声明的指针,而不是指针在 main() 中。

我应该如何将指针传递给函数并为传递的指针分配内存从被调用函数内部


我编写了以下代码并得到了如下所示的输出。

来源:

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

程序输出:

Point1: Memory allocated ptr: 262144 bytes
Point2: Memory allocated input_image: 0 bytes

最佳答案

How should I pass a pointer to a function and allocate memory for the passed pointer from inside the called function?

问问自己:如果您必须编写一个必须返回 int 的函数,您会怎么做?

你要么直接返回:

int foo(void)
{
    return 42;
}

或者通过添加级别indirection 通过输出参数返回它(即,使用 int* 而不是 int):

void foo(int* out)
{
    assert(out != NULL);
    *out = 42;
}

所以当你返回一个指针类型(T*)时,它是一样的:你要么直接返回指针类型:

T* foo(void)
{
    T* p = malloc(...);
    return p;
}

或者您添加一个间接级别:

void foo(T** out)
{
    assert(out != NULL);
    *out = malloc(...);
}

关于C 编程 : malloc() inside another function,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2838038/

相关文章:

c - 在 C 中反转列表后打印单链表的问题

javascript 对象 - 如何绑定(bind)到 "this"

c - C 中是否有可能有一个函数将这两个结构作为参数?

pointers - 我们应该在 "fundamentals of programming"类(class)中教授指针吗?

c - 从二维字符数组指针获取字符,该指针是 C 中结构指针的属性

c++ - 无法在类中初始化 unique_ptr 的 vector

c - syncfs 是否等到光盘写入完成?

c - Winpcap 代码 - 捕获在循环中丢失数据包

C 检查 NULL 和错误处理

javascript - 为什么这个简单的功能不起作用