[comp.lang.c] curses/malloc bug?

cpdnb@marlin.jcu.edu.au (David Bonnell) (02/25/91)

Machine:	DECstation 5000
OS:		Ultrix 4.0
Compiler:	cc, gcc1.37.1 OSF 1.9.2.14
			[cc -o test test.c -ltermcap -lcursesX]

Problem Desription:

	There appears to be a bug with the curses library when used with
malloc/realloc.  The following code causes a segmentation fault in the
wgetch() routine - HELP!!!


-Dave Bonnell
cpdnb@marlin.jcu.edu.au


-----------------------------------------------------------------------
#include <cursesX.h>

typedef struct {
  int	x;
  int	y;
  int	width;
  int	editable;
  char  *prompt;
  char	*def;
  char	id;
  char  *value;
} ENTRY;

extern char	*malloc(unsigned);
extern char	*realloc(char *, unsigned);
extern char	*strcpy(char *, char *);

void DB(ENTRY *, int);

static char	*dupstr(char *);
static ENTRY	*scr;
static int	entries;


void main(int argc, char **argv)
{
  int	i;

  scr = NULL;
  for (i=0; i<2; i++)
    if (scr) {
      scr = (ENTRY *)realloc((char *)scr, (i+1)*sizeof(ENTRY));
      if (scr == NULL)
	printf("REALLOC FAILED!!!!!\n\n");
    }
    else
      scr= (ENTRY *)malloc(sizeof(ENTRY));

  scr[0].x = 0;
  scr[0].y = 7;
  scr[0].width = 40;
  scr[0].editable = 1;
  scr[0].prompt = dupstr("       Name: ");
  scr[0].def = NULL;
  scr[0].id = 'N';

  entries = 2;
  DB(scr, entries);
}


static char *dupstr(char *str)
{
  char	*new;

  if (!str) {
    fprintf(stderr, "Error: dupstr() called with empty string.\n");
    exit(1);
  }

  new = (char *)malloc(strlen(str) + 1);
  if (new == NULL) {
    fprintf(stderr, "Error: dupstr() unable to malloc %d bytes.\n",
	      strlen(str));
    exit(1);
  }
  strcpy(new, str);
  return new;
}


void DB(ENTRY *scr, int entries)
{
  char	ch;

  initscr();
  clear();
  nonl();
  cbreak();
  noecho();
  keypad(stdscr, TRUE);
  refresh();

  while ((ch=getch()) == ERR);

  nl();
  nocbreak();
  nodelay(stdscr, FALSE);
  echo();
  keypad(stdscr, FALSE);
}