小编Fra*_*ata的帖子

如何正确使用 sizeof 来衡量要 malloc 的块?

假设我有一个简单的结构,包括一些指针:

typedef struct Type {
    uint32_t* intArrayPointer;
} Type;
Run Code Online (Sandbox Code Playgroud)

malloc struct 指针的正确方法是什么?由于两种方式都有效,我假设两者之一确实分配了比需要更多的内存:

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

作为参考,如何在代码中使用它:

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

int main() {
    Type* pt = newType();
    //do Stuff
    freeType(pt);
}
Run Code Online (Sandbox Code Playgroud)

c malloc struct pointers sizeof

1
推荐指数
1
解决办法
53
查看次数

标签 统计

c ×1

malloc ×1

pointers ×1

sizeof ×1

struct ×1