problem with malloc (Irix 3.3.1)

Scott Henry scotth at harlie.corp.sgi.com
Thu Oct 25 08:18:17 AEST 1990


In article <1658 at merlin.bhpmrl.oz.au>, ianh at bhpmrl.oz.au (Ian Hoyle) writes:
|> I've got an ongoing (well it was there with 3.2.2 and we just went to
|> 3.3.1 today) problem with malloc. The application in question is
|> Rich Burridge's mp postscript filter program, patchlevel 13.
[details deleted]

(having just gone through this...) The problem with debugging malloc errors is that the culprit is never the call that bombs. The culprit is a previously malloc()ed piece of memory. The layout of a malloc()ed memory is basically a header (containing some pointers to maintain the free list), followed by the area actually allocated, followed by the next header, etc. Writing past the end of the allocated memory will step on the next header. This is frequently caused by the following code fragment:

	char *ptr = (char *)malloc((u_int)(strlen(s)));
	strcpy(ptr,s);

Because of the existence of the header, the actual amount allocated is rounded up to some boundary (frequently long (4-byte) or double(8-byte)). Therefore, 75% or 87.5% of the time, there is room for that pesky trailing null even though you didn't allow for it. And on many architectures, the lowest address byte of the header contains a zero anyway, but on an IRIS, that byte is always >0. Putting the trailing null in that location causes a de-reference to somewhere outside any of the data segments, and you 


get a segmentation violation when you attempt to malloc or free the memory area whose header just got stepped on. 

My first step to fixing these kind of problems has become:

grep 'alloc(.*strlen' *.c
grep '(char *\*).*alloc(' *.c

(make sure you get all of the source files), and ensure that every occurence
of mallocing string storage includes space for the null.

I could go on, but I think you get the picture. Just to repeat: the call to malloc() or free() that causes the segmentation violation is _NEVER_ the one at fault. (Assuming you're not doing funky casts and stuff).

-- 
 Scott Henry <scotth at sgi.com> / Traveller on Dragon Wings
 Information Services,       / Help! My disclaimer is missing!
 Silicon Graphics, Inc      / 'Under-achiever and proud of it!' -- Bart Simpson



More information about the Comp.sys.sgi mailing list