简体   繁体   English

检查 malloc/calloc 的分配

[英]Checking Allocation Of malloc/calloc

It seems as a good programing practice to check each time after using malloc/calloc if an address was asagin.每次使用 malloc/calloc 后检查地址是否为 asagin 似乎是一个很好的编程实践。

Is there an option to create a function to check if the allocation succeed?是否可以创建一个函数来检查分配是否成功? as we cast we cast the type of the point each time, so the function will not know which pointer type is it.当我们转换时,我们每次都转换点的类型,所以函数不会知道它是哪种指针类型。

For example:例如:

newUser -> name = (char*)malloc(NAME_LENGTH*sizeof(char));
    if (newUser -> name == NULL){
        printf("Allocation of newUser failed\n");
        exit(1);
    } 

User *newUser = (User*)malloc(sizeof(User));
    if(newUser == NULL){
        printf("Allocation of newUser failed\n");
        exit(1);
    }

Can a function be created that gets newUser and newUser -> name and will exit if allocation failed?是否可以创建一个函数来获取 newUser 和 newUser -> name 并在分配失败时退出?

First, don't cast the return value of malloc as it can hide other errors.首先, 不要malloc的返回值,因为它可以隐藏其他错误。

There's no problem wrapping malloc in a function that will do the null check for you.malloc包装在一个可以为您进行空检查的函数中没有问题。 Since malloc takes a size_t and returns a void * your wrapper function should do the same.由于malloc需要一个size_t并返回一个void *你的包装函数应该做同样的事情。 For example:例如:

void *safe_malloc(size_t s)
{
    void *p = malloc(s);
    if (!p) {
        perror("malloc failed");
        exit(1);
    }
    return p;
}

Then you can use this function anyplace you use malloc without having to explicitly do a NULL check.然后,您可以在任何使用malloc地方使用此函数,而无需显式执行 NULL 检查。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM