delorie.com/archives/browse.cgi   search  
Mail Archives: djgpp/1998/01/19/19:44:21

From: mlcrowd AT mail DOT enol DOT com
Message-Id: <199801170348.UAA25385@mail.enol.com>
Comments: Authenticated sender is <mlcrowd@[208.128.142.72]>
To: djgpp AT delorie DOT com
Date: Fri, 16 Jan 1998 20:04:07 +0000
MIME-Version: 1.0
Subject: Malloc problem

Hi,

  I'm writing a tile-based mapping system, and I've come up with a bit
of a problem:  I'm using layers for my maps, and when I try to access
the layers (after they've been allocated with malloc), I get a page
fault.  Here's some code to (hopefully) make it easier to understand:

typedef struct
{
  short* data;
} LAYER;

typedef struct
{
  short width, height;
  short num_layers;
  LAYER* layers;
} TMap;

Then I allocate it like this (map is of type TMap):

if (!(map.layers = (LAYER*)malloc(sizeof(LAYER) * map.num_layers))) {
  allegro_exit();

  printf("Error allocating memory for layers!\n");
  exit(-1);
}

for (i=0; i<map.num_layers; i++)
{
  if (!(map.layers[i].data = (short*)malloc(sizeof(short) * 
      (long)map.width * map.height)))
  {
    allegro_exit();

    printf("Error allocating memory for layers!\n");
    exit(-1);
  }
}

That part works fine (at least I think so).  But whenever I access
map.layers[].data[], I get a page fault (I've tried various values for
between the brackets).  For example, when I try this, it crashes:

  map.layers[0].data[0] = 1;

If I understand correctly, this should set the data member of the
layers[] member of the map structure (sorry about this sentence... ;))
to 1.  

I _have_ tried using a two dimensional array instead (i.e.: 
map.data[cur_layer][y*width+x]), but that doesn't work either.  If
anybody has any suggestions (for either the structure method or the
two dimensional array method), I would greatly appreciate it.

Thanks in advance!

Ben <mlcrowd AT enol DOT com>

- Raw text -


  webmaster     delorie software   privacy  
  Copyright © 2019   by DJ Delorie     Updated Jul 2019