cscg22-gearboy

CSCG 2022 Challenge 'Gearboy'
git clone https://git.sinitax.com/sinitax/cscg22-gearboy
Log | Files | Refs | sfeed.txt

calloc.c (2162B)


      1/*-------------------------------------------------------------------------
      2   calloc.c - allocate memory.
      3
      4   Copyright (C) 2015, Philipp Klaus Krause, pkk@spth.de
      5
      6   This library is free software; you can redistribute it and/or modify it
      7   under the terms of the GNU General Public License as published by the
      8   Free Software Foundation; either version 2, or (at your option) any
      9   later version.
     10
     11   This library is distributed in the hope that it will be useful,
     12   but WITHOUT ANY WARRANTY; without even the implied warranty of
     13   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
     14   GNU General Public License for more details.
     15
     16   You should have received a copy of the GNU General Public License 
     17   along with this library; see the file COPYING. If not, write to the
     18   Free Software Foundation, 51 Franklin Street, Fifth Floor, Boston,
     19   MA 02110-1301, USA.
     20
     21   As a special exception, if you link this library with other files,
     22   some of which are compiled with SDCC, to produce an executable,
     23   this library does not by itself cause the resulting executable to
     24   be covered by the GNU General Public License. This exception does
     25   not however invalidate any other reasons why the executable file
     26   might be covered by the GNU General Public License.
     27-------------------------------------------------------------------------*/
     28
     29#include <stdlib.h>
     30#include <string.h>
     31#include <stdint.h>
     32
     33#if defined(__SDCC_mcs51) || defined(__SDCC_ds390) || defined(__SDCC_ds400)
     34#define HEAPSPACE __xdata
     35#elif defined(__SDCC_pdk13) || defined(__SDCC_pdk14) || defined(__SDCC_pdk15)
     36#define HEAPSPACE __near
     37#else
     38#define HEAPSPACE
     39#endif
     40
     41#if defined(__SDCC_mcs51) || defined(__SDCC_ds390) || defined(__SDCC_ds400)
     42void HEAPSPACE *calloc (size_t nmemb, size_t size)
     43#else
     44void *calloc (size_t nmemb, size_t size)
     45#endif
     46{
     47	void HEAPSPACE *ptr;
     48
     49	unsigned long msize = (unsigned long)nmemb * (unsigned long)size;
     50
     51	_Static_assert(sizeof(unsigned long) >= sizeof(size_t) * 2,
     52		"size_t too large wrt. unsigned long for overflow check");
     53
     54	if (msize > SIZE_MAX)
     55		return(0);
     56
     57	if (ptr = malloc(msize))
     58		memset(ptr, 0, msize);
     59
     60	return(ptr);
     61}
     62