This is the mail archive of the mailing list for the glibc project.

Index Nav: [Date Index] [Subject Index] [Author Index] [Thread Index]
Message Nav: [Date Prev] [Date Next] [Thread Prev] [Thread Next]

Re: problem with malloc?

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.

    #include <stdio.h>

    int lstrcpy(char *target, const char *source, size_t targetbufsize)
	return sprintf(target, "%.*s", (int) (targetbufsize - 1), source);

Index Nav: [Date Index] [Subject Index] [Author Index] [Thread Index]
Message Nav: [Date Prev] [Date Next] [Thread Prev] [Thread Next]