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/26820928/

相关文章:

c - 如何防止一个进程使用另一个进程使用的内存?

c - 指向指针或全局变量的指针?

C 预处理器可以执行算术运算吗?如果可以,如何执行?

R重命名函数中传递的列

javascript - 如何改进我的代码(连接函数中的参数) - JavaScript 初学者

c++ - 使用基于范围的 for 循环动态创建的对象显示为 nullptr

pointers - 如何判断Fortran过程指针是否与特定子程序关联

c - 在 Linux 中通过 perf 为未列出的功能添加动态跟踪点

mysql - PL-SQL - 我可以将枚举作为函数参数传递吗?

c - 不同数据类型中的指针行为