1

I have a struct that looks like this:

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

and a corresponding constructor:

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

Now say I want to have another function that calls the constructor and returns a pointer to the 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;
}

Is this well-defined behaviour aka is dostuff guaranteed to exist after the function returns?

Sourav Ghosh
  • 133,132
  • 16
  • 183
  • 261
lord.garbage
  • 5,884
  • 5
  • 36
  • 55
  • C does not have constructors. Their semantics are different from functions. – too honest for this site Jul 23 '15 at 13:40
  • Yes, I know. If it bothers you, mentally substitute "`C` function in the style of a constructor". – lord.garbage Jul 23 '15 at 13:42
  • That is a factory function. A constructor is a method bound to an existing (but uninitialized) object. – too honest for this site Jul 23 '15 at 13:43
  • @Olaf, please, feel free to edit. – lord.garbage Jul 23 '15 at 13:44
  • Doing OOP in C, this is the most commonly used form of a "constructor replacement". It's technically *just a function*, neither a factory function (that would give you potentially different concrete types) nor a constructor (that would be called automatically after allocation). Semantically, it is a constructor that (as an implementation detail) does its own allocation. –  Jul 23 '15 at 13:58

1 Answers1

4

Yes, it is not undefined behaviour.

In your code, dostuff is holding a pointer returned by malloc(). It's lifetime is spanned until deallocated manually , like using free(). So, returning dostuff and using it later is all good.

Sourav Ghosh
  • 133,132
  • 16
  • 183
  • 261