从另一个函数调用构造函数时的存储持续时间

Storage duration when calling constructor from another function

我有一个看起来像这样的结构:

struct matrix {
    size_t nrow;
    size_t ncol;
    double *data;
};

和相应的构造函数:

struct matrix *matrix_create(const size_t nrow, const size_t ncol)
{
    struct matrix *m;

    m = malloc(sizeof(struct matrix));
    if (!m) {
        fprintf(stderr, "Memory allocation failed\n");
        return NULL;
    }
    m->data = malloc(sizeof(double) * nrow * ncol);
    if (!m->data) {
        fprintf(stderr, "Memory allocation failed\n");
        return NULL;
    }

    m->nrow = nrow;
    m->ncol = ncol;

    return m;
}

现在假设我想要另一个调用构造函数的函数和 returns 指向 struct:

的指针
struct matrix *matrix_dostuff(const struct matrix *m1, const struct matrix *m2)
{
    struct matrix *dostuff =
        matrix_create(m1->nrow * m2->nrow, m1->ncol * m2->ncol);

    /* do stuff */

    return dostuff;
}

这种定义明确的行为是否 dostuff 保证在函数 returns 之后存在?

是的,这不是未定义的行为。

在您的代码中,dostuff 持有 malloc() 返回的指针。它的生命周期一直持续到手动释放为止,例如使用 free()。所以,返回 dostuff 并在以后使用它就可以了。