Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ISO C equivalent of braced-groups within expressions

Tags:

c

gcc

macros

How can I do the following in a compliant (ISO C99) way?

#define MALLOC(type, length, message) ({                                      \
         type * a_##__LINE__ = (type *)malloc((length) * sizeof(type));       \
         assert(message && (a_##__LINE__ != NULL));                           \
         a_##__LINE__;                                                        \
      })

double **matrix = MALLOC(double *, height, "Failed to reserve");

NB: to compile I use: gcc -std=c99 -pedantic ...

like image 475
Alexandru Avatar asked Oct 26 '09 18:10

Alexandru


1 Answers

You shouldn't put the test for malloc() in an assert(): it won't be compiled in when you do a release build. I haven't used assert() in the following program.

#include <stdio.h>
#include <stdlib.h>

void *mymalloc(size_t siz, size_t length,
               const char *message, const char *f, int l) {
  void *x = malloc(siz * length);
  if (x == NULL) {
    fprintf(stderr, "a.out: %s:%d: MALLOC: "
                    "Assertion `\"%s\" && x != ((void *)0)' failed.\n",
          f, l, message);
    fprintf(stderr, "Aborted\n");
    exit(EXIT_FAILURE);
  }
  return x;
}

#define MALLOC(type, length, message)\
      mymalloc(sizeof (type), length, message, __FILE__, __LINE__);

int main(void) {
  int height = 100;
  double **matrix = MALLOC(double *, height, "Failed to reserve");
  /* work; */
  free(matrix);
  return 0;
}
like image 84
pmg Avatar answered Sep 22 '22 17:09

pmg