File indexing completed on 2024-12-08 08:09:29
0001 // clang-format off 0002 /* xmalloc.c -- malloc with out of memory checking 0003 0004 Modified for KDiff3 by Joachim Eibl 2003. 0005 The original file was part of GNU DIFF. 0006 0007 0008 Part of KDiff3 - Text Diff And Merge Tool 0009 0010 SPDX-FileCopyrightText: 1988-2002 Free Software Foundation, Inc. 0011 SPDX-FileCopyrightText: 2002-2011 Joachim Eibl, joachim.eibl at gmx.de 0012 SPDX-FileCopyrightText: 2018-2020 Michael Reeves reeves.87@gmail.com 0013 SPDX-License-Identifier: GPL-2.0-or-later 0014 */ 0015 // clang-format on 0016 0017 #include <stdlib.h> 0018 #include <string.h> 0019 0020 #ifndef EXIT_FAILURE 0021 #define EXIT_FAILURE 1 0022 #endif 0023 0024 #include "gnudiff_diff.h" 0025 /* If non NULL, call this function when memory is exhausted. */ 0026 void (*xalloc_fail_func)() = nullptr; 0027 0028 void GnuDiff::xalloc_die() 0029 { 0030 if(xalloc_fail_func) 0031 (*xalloc_fail_func)(); 0032 //error (exit_failure, 0, "%s", _(xalloc_msg_memory_exhausted)); 0033 /* The `noreturn' cannot be given to error, since it may return if 0034 its first argument is 0. To help compilers understand the 0035 xalloc_die does terminate, call exit. */ 0036 exit(EXIT_FAILURE); 0037 } 0038 0039 /* Allocate N bytes of memory dynamically, with error checking. */ 0040 0041 void * 0042 GnuDiff::xmalloc(size_t n) 0043 { 0044 void *p; 0045 0046 p = malloc(n == 0 ? 1 : n); // There are systems where malloc returns 0 for n==0. 0047 if(p == nullptr) 0048 xalloc_die(); 0049 return p; 0050 } 0051 0052 /* Change the size of an allocated block of memory P to N bytes, 0053 with error checking. */ 0054 0055 void * 0056 GnuDiff::xrealloc(void *p, size_t n) 0057 { 0058 p = realloc(p, n == 0 ? 1 : n); 0059 if(p == nullptr) 0060 xalloc_die(); 0061 return p; 0062 } 0063 0064 /* Yield a new block of SIZE bytes, initialized to zero. */ 0065 0066 void * 0067 GnuDiff::zalloc(size_t size) 0068 { 0069 void *p = xmalloc(size); 0070 memset(p, 0, size); 0071 return p; 0072 }