malloc() problem on sysv386

Jeff Turner jeff at uf.msc.umn.edu
Sat May 25 08:05:54 AEST 1991


In article <1991May23.094026.18969 at hollie.rdg.dec.com> moore at forty2.enet.dec.com (Paul Moore) writes:
>I've recently had this error occuring when malloc is called running an
>application on ISC SVR3.2 (observed from the sdb debugger):
>
>   memory fault (11) (sig 11)
>
>The man page for signal(3) indicates that this is a segmentation violation. 
>
>The problem only occurs when malloc() had been previously called in the code
>execution path; it doesn't appear when this code path isn't executed.
>
>The problem doesn't appear at all when I run the very same application on
>Ultrix.
>
>Any ideas, anyone?
>
>- Paul
>

The frequent cause of malloc problems that I have observed are from programmers
malloc'ing a buffer for a string based on the string's strlen() (rather than
its real length), and then copying the string into it (which can overwrite
malloc's tables).

What I mean is simply that if you are going to malloc a buffer for a string,
you have to have to make sure you allocate room for the zero byte that 
terminates the string:

Wrong:
	cp = "string";
	new_cp = malloc(strlen(cp));
	strcpy(new_cp, cp);

Right:
	cp = "string";
	new_cp = malloc(strlen(cp)+1);
	strcpy(new_cp, cp);

The fact that the problem goes away when you change hardware platforms
suggests it might be something as simple as what I described.  Different
hardware platforms (for their own reasons) will sometimes pad your request out
to some memory specific alignment (e.g CRAYs pad out to an 8-byte word).
So, if you ask for 4 bytes, and malloc gives you 8, you won't get caught if
you write 1 byte past what you asked for.  However, if you ask for 8 (and 
get 8) you cannot write to the next byte without stomping on malloc's
information.  Likewise, if your take you code to another machine that pads 
mallocs out to 4 byte alignements, the use of the 5th byte will stomp on
malloc's tables (i.e. this is how the same code could produce different
results on different machines).

Most of people I have seen do this know better, but they make the mistake
anyway.  For most people, it is more of a typo than a programming error.


Hope this helps, at least it is something to look for.

-Jeff
---
Jeff Turner                           EMAIL: jeff at msc.edu
Minnesota Supercomputer Center, Inc.  VOICE: (612) 626-0544
Minneapolis, Minnesota  55415           FAX: (612) 624-6550



More information about the Comp.unix.sysv386 mailing list