[Courses] [C Doubt]

Conor Daly c.daly at met.ie
Thu Sep 19 08:55:22 EST 2002


On Wed, Sep 18, 2002 at 09:58:16PM -0700 or thereabouts, Akkana wrote:
> 
> This works fine, but you're allocating more memory than you need ...
> you really only need (e - s + 1) bytes (+1 because you'll probably
> want to write a null at the end, since most functions that take strings
> expect them to be null-terminated).  This also has the nice bonus
> of making the function a little faster since you don't need to call
> strlen() (which has to loop over str to find out how long it is).
> 
> So I'd suggest modifying your function very slightly:
> 
>   str1=(char *)malloc(e-s+1);
                       ^^^^^^^

Maybe be explicit about the order of evaluation here.  In this case, 

y = (e - s + 1)

will evaluate as

x = e - s

followed by

y = x + 1

so all is well but for other operations you could get caught.  eg.

y = (e - s * 2)

evaluates as

x = s * 2
y = e - x

instead

y = ((e - s) * 2)

evaluates as 

x = e - s
y = x * 2

I _personally_ would use

y = ((e - s) + 1)

in the malloc.  It doesn't make any difference here but being in the habit
of explicitly specifying the order of evaluation avoids bugs in more complex
formulae

Conor
-- 
Conor Daly 
Met Eireann, Glasnevin Hill, Dublin 9, Ireland
Ph +353 1 8064276 Fax +353 1 8064247
------------------------------------
bofh.irmet.ie running RedHat Linux  8:48am  up 6 days, 21:31,  4 users,  load average: 0.19, 0.23, 0.14


**********************************************************************
This email and any files transmitted with it are confidential and
intended solely for the use of the individual or entity to whom they
are addressed. If you have received this email in error please notify
the system manager.

This footnote also confirms that this email message has been swept 
for the presence of computer viruses.


**********************************************************************




More information about the Courses mailing list