Frank Pirata
Frank Pirata

Reputation: 55

How do I properly use sizeof to measure the block to malloc?

Assume I have a simple struct, including some pointers:

typedef struct Type {
    uint32_t* intArrayPointer;
} Type;

What is the correct way, to malloc the struct pointer? As both ways work, I assume one of the two does allocate more memory than needed:

  1.  Type* newType() {
         Type* returnPointer = malloc(sizeof(Type));
         returnPointer->intArrayPointer = malloc(sizeof(uint32_t)*128);
         return returnPointer;
     }
    
  2.  Type* newType() {
         Type* returnPointer = malloc(sizeof(Type*));
         returnPointer->intArrayPointer = malloc(sizeof(uint32_t)*128);
         return returnPointer;
     }
    
    

For reference, how this would be used in Code:

void freeType(Type* this) {
    free(this->intArrayPointer);
    free(this);
}

int main() {
    Type* pt = newType();
    //do Stuff
    freeType(pt);
}

Upvotes: 1

Views: 88

Answers (1)

Sourav Ghosh
Sourav Ghosh

Reputation: 134346

The best way would be to use

Type* returnPointer = malloc(sizeof(*returnPointer));

or, better,

Type* returnPointer = malloc(sizeof *returnPointer); 
            // parenthesis is needed only when argument is a type, 
            // not needed for expressions used as argument

which does not depend on the type at all.

Same way, you should do for intArrayPointer, too. And don't forget to check for the success of the calls, too.

Upvotes: 7

Related Questions