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

Re: [MiNT] Question about memory under MagiC



On Sunday 23 Oct 2011 01:26:41 Jo Even Skarstein wrote:
> 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.

Good idea. I will try this.
 
> 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.

1st thing I did, of course. They're equal. That's why I wrote in my 1st 
message that I was sure both destination and source were at equal length.

> 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 ;)

I'm not doing either :-) And you are right that allocating to the exact amount 
in this context is not that useful and somewhat complicates the code.

Thanks for the time, Jo Even. This is really appreciated.

Cheers,
JFL
-- 
Jean-François Lemaire