Macro for allocation in C As we all know, the syntax of allocating memory is a bit clunky in C. The recommended way is:

 int *p;
 int n=10;
 p = malloc(n*sizeof *p);


You can use sizeof (int) instead of sizeof *p but it is bad practice.

I made a solution to this with a macro:

#define ALLOC(p,n) do{ *p=malloc(n*sizeof **p); } while(0)


This get called this way:

 int *p;
 int n=10;
 ALLOC(&amp;p, n);


The reason I want to pass the address of p rather than p, is to offer a bit of protection. When you call a function with foo(x), then foo can never change the value of x. If you're not passing the address, the argument will not change. (Sure there are ways around that too.)

Any comments?
p = malloc(n*sizeof *p);


This is dangerous if n gets large, because the multiplication could overflow. After the overflow, too little memory has been allocated but code will continue without detecting the error.

This is especially dangerous if n comes from untrusted source, such as some file format or remote user. Then it gives attacker easy way to overwrite parts of memory with exploit code.

The easy safe solution is to use calloc() which will detect the overflow (at least on most common libc implementations). If you really need to use malloc() for some reason, you can check for overflow separately.