This is the mail archive of the
glibc-linux@ricardo.ecn.wfu.edu
mailing list for the glibc project.
Re: problem with malloc?
- To: Kaz Kylheku <kaz at ashi dot footprints dot net>
- Subject: Re: problem with malloc?
- From: fheitka at attglobal dot net
- Date: Sat, 22 Apr 2000 06:03:59 -0400
- Cc: glibc-linux at ricardo dot ecn dot wfu dot edu
- Reply-To: glibc-linux at ricardo dot ecn dot wfu dot edu
In <Pine.LNX.4.10.10004211929460.13640-100000@ashi.FootPrints.net>, on
04/21/00
at 07:44 PM, Kaz Kylheku <kaz@ashi.footprints.net> said:
>On Fri, 21 Apr 2000, Fred Heitkamp wrote:
>> Got electric fence. Thanks!
>>
>> I found the problem. It was a buffer overrun in strcpy.
>>
>> My data file that my program reads was written by a fortran program
>> I think. Strlen seems to give the correct answer as far as actual number
>> of characters (20) , but strcpy tries to copy the whole line which is
>> 62 characters. Probably the length of the fortran record.
>That is simply not possible. If strlen returns 20, then strcpy will copy
>20 bytes plus one null byte.
>> I put strncpy for strcpy and the program runs fine.
I just didn't do a blind substitution. I change the code to essentially
this:
len = strnlen( buffer );
target = ( char * )malloc( (len+1)*sizeof( char ) );
strncpy( target, buffer, len );
>You can't blindly substitute one for the other. The strncpy function does
>not ensure null termination of the target array in all cases.
Yeah I know. I read the man page. I wasn't too worried about the NULL
termination right at the moment. I wanted to find the source of the seg.
fault. I think I could just do something like
strcat( target ,'\0' );
assuming the target buffer is big enough that is.
>The sprintf function can be leveraged to do a limited copy with proper
>null termination, though this in itself is tricky enough to be wrapped
>with a macro or function.
> #include <stdio.h>
> int lstrcpy(char *target, const char *source, size_t targetbufsize)
> {
> return sprintf(target, "%.*s", (int) (targetbufsize - 1), source);
> }
Do you think the disparity in calculating the len, strlen vs
what strcpy does is a bug? Probably not, but I thought I'd
ask.
Fred