This is the mail archive of the
mailing list for the glibc project.
Re: problem with malloc?
- To: glibc-linux at ricardo dot ecn dot wfu dot edu
- Subject: Re: problem with malloc?
- From: Kaz Kylheku <kaz at ashi dot footprints dot net>
- Date: Fri, 21 Apr 2000 19:44:24 -0700 (PDT)
- cc: fheitka at attglobal dot net
- Reply-To: glibc-linux at ricardo dot ecn dot wfu dot edu
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.
You can't blindly substitute one for the other. The strncpy function does not
ensure null termination of the target array in all cases.
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.
int lstrcpy(char *target, const char *source, size_t targetbufsize)
return sprintf(target, "%.*s", (int) (targetbufsize - 1), source);