[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: [MiNT] Question about memory under MagiC



On Sun, 2011-10-23 at 00:21 +0200, Jean-François Lemaire wrote:

> > You should either add 1 to the return value if positive, or use
> > strlen().
> 
> I *am* adding 1. In the example above, PATHSIZE = 256, and string1 and string2 
> are around 20 at max. Overflow is definitely out of the question.

No, it's not. The error message from MagiC *is* an overflow. PATHSIZE
doesn't mean anything because the error message comes from overwriting
the end of your Mxalloc-ed memory, and the size of that block has
nothing to do with PATHSIZE.

I'm sure you can verify this behaviour under MiNT as well. Be a bit
naughty and write a #ff one byte beyond your Mxalloc'ed buffer, and see
if it's still there after the strcpy.

Btw I missed the "+1" from your code, I see that now. But please check
the *actual* return value from snprintf and compare it to the return
value from strlen on the same string.

If I were you, I would have rewritten this code to something like this:

char path[PATHSIZE] = {0};

if (snprintf(path, sizeof path, "%s%s", string1, string2) < 0)
{
	// An error occured, path was too small. Handle it.
}
else
{
	char *p = Mxalloc(global, strlen(path) + 1);
	if (p)
		strcpy(p, path);
}

...or simply do a Mxalloc(global, PATHSIZE). 256 bytes or 40 bytes, that
doesn't matter unless you're doing an awful amount of Mxallocs (which
you shouldn't anyway) or you're programming for a microcontroller ;)
 
Jo Even