Always check malloc'ed memory?

后端 未结 10 916
滥情空心
滥情空心 2020-12-09 03:05

I often catch myself doing the following (in non-critical components):

some_small_struct *ptr=(some_small_struct *) malloc(sizeof(some_small_struct));
ptr-&g         


        
10条回答
  •  鱼传尺愫
    2020-12-09 03:35

    Assuming that you are running on a Linux/MaxOs/Windows or other virtual memory system, then... the only reason to check the return value from malloc is if you have a strategy for freeing up enough memory to allow the program to continue running. An informative message will help in diagnosing the problem, but only if your program caused the out-of-memory situation. Usually it is not your program and the only thing that your program can to do help is to exit as quickly as possible.

    assert(ptr != NULL);
    

    will do all of these things. My usual strategy is to have a layer around malloc that has this in it.

    void *my_malloc(size_t size)
    {
        void *ptr = malloc ( size );
        assert(ptr != NULL);
        return *ptr;
    }
    

    Then you call my_malloc instead of malloc. During development I use a memory allocation library that is conducive to debugging. After that if it runs out of memory - I get a message.

提交回复
热议问题