segmentation fault when allocating memory with new or malloc

lrtaylor@micron.com lrtaylor@micron.com
Tue Jan 13 19:23:00 GMT 2004


Have you tried looking at a stack trace to see where your program is actually crashing?  With the core file, you can even look at the value of variables, etc.  Whenever I get a segmentation fault, the first thing I do is look at the stack trace to see where it happened.

If you've never looked at a stack trace before, then you should probably take a look at the manual for GDB.  They have a section on examining the stack.  You'll also need to make sure that your programs are generating a core file when they crash.  RedHat seems to have turned this off by default, but you can reenable it in the current shell using the ulimit command:

ulimit -c unlimited

Otherwise, I concur with what another poster said - you've probably corrupted memory before ever getting to this point, and this is just bringing the problem out.  I would go over your code with a fine-toothed comb and look for any problems with pointers.

Good luck,
Lyle

-----Original Message-----
From: gcc-help-owner@gcc.gnu.org [mailto:gcc-help-owner@gcc.gnu.org]On
Behalf Of Tobias Kretz
Sent: Tuesday, January 13, 2004 3:32 AM
To: gcc-help@gcc.gnu.org
Subject: segmentation fault when allocating memory with new or malloc


Hi,

allocating memory with one of these lines:

pl=(list*)malloc((v)*sizeof(list));
or
list*pl; pl=new list[v];

causes the program to be terminated by a segmentation fault.
v is an integer that equals e.g. 7 in my test runs (thus far from 
throwing a bad_alloc)

and list is trivially:
  struct list{
  	     int x;
	     int y;
	  double d;
	    };

Replacing the variable v by a constant value does not improve the 
situation.
Also:
  cout << "A\n";
  try {pl=new list[v];}
  catch(bad_alloc) {cerr<< "not enough memory\n";}
  cout << "B\n";
results in the output:
A
Segmentation fault

Additionally weird is that omitting the memory allocation
makes the program run further. Yet it crashes with a seg fault.
when trying to set up an outfile stream:
bmpofstream image("floor.bmp",xmax,ymax);
later in the program. The rest of the program contains datastructures 
for which I allcoate some 100kB memory (with new).

I use g++, gcc version 3.2.2 20030222 (Red Hat Linux 3.2.2-5)

Regards,
ToK



More information about the Gcc-help mailing list