Communities

Writing
Writing
Codidact Meta
Codidact Meta
The Great Outdoors
The Great Outdoors
Photography & Video
Photography & Video
Scientific Speculation
Scientific Speculation
Cooking
Cooking
Electrical Engineering
Electrical Engineering
Judaism
Judaism
Languages & Linguistics
Languages & Linguistics
Software Development
Software Development
Mathematics
Mathematics
Christianity
Christianity
Code Golf
Code Golf
Music
Music
Physics
Physics
Linux Systems
Linux Systems
Power Users
Power Users
Tabletop RPGs
Tabletop RPGs
Notifications
Mark all as read
Q&A

When does it not work to dereference the pointer for sizeof during malloc?

+6
−0

Background

This is kind of a subquestion to How to properly use malloc?

When allocating, there are basically two common ways of using the sizeof operator:

int *p;
p = malloc(n * sizeof *p);   // Method 1: Dereference the pointer
p = malloc(n * sizeof(int)); // Method 2: Explicitly use the type

I personally prefer method 1, because it reduces code duplication.* And the rule is pretty simple. Take whatever you have on the left of the equal sign, and add an asterisk to get the argument for sizeof. It also works for 2D or 3D:

int ***p;
p = malloc(x * sizeof *p); // Add asterisk to p
for(int i=0; i<x; i++) {
    p[i] = malloc(y * sizeof *p[i]); // Add asterisk to p[i]
    for(int j=0; j<y; j++) {
        p[i][j] = malloc(z * sizeof *p[i][j]); // Add asterisk to p[i][j]
    }
}

* In the sense that if you have multiple malloc calls where you assign to the pointer p, then if you want to change the type of the pointer, you would need to find ALL malloc calls and change them.

Array parameters

I know of one instance where it "doesn't work", and that is when you have complex parameters to functions. Like this:

void foo(int n, int32_t p[5][5]) {

But in this case, I'd say that the problem is that when arrays are declared as function arguments like that, they are not arrays. Indeed, the C syntax here is a bit strange. The equivalent declaration int32_t (*p)[5] works as expected with this rule. Because the type of p is pointer to array 5 of int32_t. In other words, I expect sizeof *p to be 20, which it also is. The solution to the above problem is to - explicitly in code or mentally in your head - introduce a temporary variable:

void foo(int n, int32_t p[5][5]) {
    int32_t (*tmp)[5];
    tmp = malloc(n * sizeof *tmp);

void pointers

I know that it does not work if you have void pointers. For example:

void *p;
p = malloc(n * sizeof *p); // Error: A void pointer cannot be dereferenced
p = malloc(sizeinbytes);   // Works fine

However, even if this isn't a very extreme and unusual case, this is indeed a pretty special case. And it's also pretty obvious that it's an exception. A C programmer should know that void pointers cannot be dereferenced. However, do note that both gcc and clang required compiling with -pedantic to warn about this.

Flexible array members

Another case is if you have a pointer to struct where the struct contains a flexible array. But although this indeed is a very valid real world use case where this approach would not work, it's also abundantly obvious that it is an exception, since the whole foundation around flexible array members is that you manually Furthermore, the rule can be shoehorned in if you want to. At least for the case where you want several instances of the struct and the flexible array equally big for each of them. Like this:

struct s {
    int x;
    char y;
    double z;
    long a[];
};

// m is how many elements the array s::a should have in each instance of s
// n is how many instances of s we want
struct s *p = malloc(n * (sizeof(*p) + m * sizeof *(p->a)));

Question

So my question is, when does this approach with just adding an asterisk to the pointer not work? I'm interested in both realistic use cases and examples created just to break this rule of thumb. Please specify if your example is a real issue or just a theoretical one.

Why does this post require moderator attention?
You might want to add some details to your flag.
Why should this post be closed?

3 comment threads

"[...] because it reduces code duplication." Does it, though? (9 comments)
De-referencing void pointers (3 comments)
Typo? (2 comments)

1 answer

+4
−0

In addition to all the examples I gave in my answer to the linked post, all scenarios where p is a pointer to incomplete type fails. Not just the void* scenario, but also when p is a pointer to an array of incomplete type:

int (*p)[] = malloc(n * sizeof *p); // will not compile cleanly

And also when using forward-declared structs/unions:

struct fwd_declared* p;
p = malloc(n * sizeof *p); // will not compile cleanly

And when using function pointers:

void (*p)(void);
p = malloc(n * sizeof *p); // will not compile cleanly

All of these examples (including de-referencing void pointers) are invalid C as per C17 6.5.3.4:

Constraints

The sizeof operator shall not be applied to an expression that has function type or an incomplete type

Regarding "compile cleanly" please see What must a C compiler do when it finds an error?

And please note that gcc/clang are by default in a non-standard mode until you pass along -std=c17 -pedantic-errors to tell them to become conforming implementations.


These are weak arguments against using a certain malloc style though.

Why does this post require moderator attention?
You might want to add some details to your flag.

1 comment thread

Nice answer. Some questions about it. (3 comments)

Sign up to answer this question »