new.cpp revision 114402
196913Sgrog/* Copyright (C) 1989, 1990, 1991, 1992, 2001, 2003
296913Sgrog   Free Software Foundation, Inc.
396913Sgrog     Written by James Clark (jjc@jclark.com)
496913Sgrog
596913SgrogThis file is part of groff.
696913Sgrog
796913Sgroggroff is free software; you can redistribute it and/or modify it under
896913Sgrogthe terms of the GNU General Public License as published by the Free
996913SgrogSoftware Foundation; either version 2, or (at your option) any later
1096913Sgrogversion.
1196913Sgrog
1296913Sgroggroff is distributed in the hope that it will be useful, but WITHOUT ANY
1396913SgrogWARRANTY; without even the implied warranty of MERCHANTABILITY or
1496913SgrogFITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
1596913Sgrogfor more details.
1696913Sgrog
1796913SgrogYou should have received a copy of the GNU General Public License along
1896913Sgrogwith groff; see the file COPYING.  If not, write to the Free Software
1996913SgrogFoundation, 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */
2096913Sgrog
2196913Sgrog#include "lib.h"
2296913Sgrog
2396913Sgrog#include <stddef.h>
2496913Sgrog#include <stdlib.h>
2596913Sgrog
2696913Sgrog#include "posix.h"
2796913Sgrog#include "nonposix.h"
2896913Sgrog
2996913Sgrogextern const char *program_name;
3096913Sgrog
3196913Sgrogstatic void ewrite(const char *s)
3296913Sgrog{
3396913Sgrog  write(2, s, strlen(s));
3496913Sgrog}
3596913Sgrog
3696911Sgrogvoid *operator new(size_t size)
3796911Sgrog{
3896911Sgrog  // Avoid relying on the behaviour of malloc(0).
3996911Sgrog  if (size == 0)
4096911Sgrog    size++;
4196911Sgrog#ifdef COOKIE_BUG
4296911Sgrog  char *p = (char *)malloc(unsigned(size + 8));
4396911Sgrog#else /* not COOKIE_BUG */
4496911Sgrog  char *p = (char *)malloc(unsigned(size));
4596911Sgrog#endif /* not COOKIE_BUG */
4696911Sgrog  if (p == 0) {
4796911Sgrog    if (program_name) {
4896911Sgrog      ewrite(program_name);
4996911Sgrog      ewrite(": ");
5096911Sgrog    }
5196911Sgrog    ewrite("out of memory\n");
5296911Sgrog    _exit(-1);
5396911Sgrog  }
5496911Sgrog#ifdef COOKIE_BUG
5596911Sgrog  ((unsigned *)p)[1] = 0;
5696911Sgrog  return p + 8;
5796911Sgrog#else /* not COOKIE_BUG */
5896911Sgrog  return p;
5996911Sgrog#endif /* not COOKIE_BUG */
6096911Sgrog}
6196911Sgrog
6296911Sgrogvoid operator delete(void *p)
6396911Sgrog{
6496911Sgrog#ifdef COOKIE_BUG
6596911Sgrog  if (p)
6696911Sgrog    free((void *)((char *)p - 8));
6796911Sgrog#else
6896911Sgrog  if (p)
6996911Sgrog    free(p);
7096911Sgrog#endif /* COOKIE_BUG */
7196911Sgrog}
7296911Sgrog