Malloc error handling

What are the possible errors that can occur when allocating memory using mallocexcept out of memory? What are the best strategies to resolve these errors?

To out of memory exceptionwhether to release the pointer, even if a failure is not fulfilled?

+5
source share
3 answers

There are no exceptions in C (but you cannot use them in any language), so the only way mallocto signal a failure is to return a null pointer. Therefore, you should check the return value. If it is 0, the distribution failed (for some reason) and no memory was allocated - do not release anything; otherwise allocating the requested amount (*) would be successful and you would need to free the memory when it is no longer needed.

(*) : malloc size_t, , , . size * sizeof(int) unsigned size (, size), . malloc() () size,

+11

, , CheckPointer, , .

+1

- ... , , .

C malloc realloc ( xmalloc xrealloc), , , ... , , , . , , . .

​​ C ( , ), ( - ;, . ). , , C ... , ++, new bad_alloc.

... malloc , NULL; . ( (NULL) - -op). realloc , . , , http://pubs.opengroup.org/onlinepubs/7908799/xsh/realloc.html

0
source

All Articles