Should I check if malloc() was successful?

前端 未结 2 755
礼貌的吻别
礼貌的吻别 2020-11-29 08:49

Should one check after each malloc() if it was successful? Is it at all possible that a malloc() fails? What happens then?

At school we were told that we should chec

2条回答
  •  执笔经年
    2020-11-29 09:24

    No need to cast malloc(). Yes it is required to check whether the malloc() was successful or not. Let's say malloc() failed and you are trying to access the pointer thinking memory is allocated will lead to crash.So it it better to catch the memory allocating failure before accessing the pointer.

    int *arr = malloc(sizeof(*arr));
    if(arr == NULL)
    {
    printf("Memory allocation failed");
    return;
    }
    

提交回复
热议问题