This is the mail archive of the
glibc-linux@ricardo.ecn.wfu.edu
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: "tjk at tksoft dot com" <tjk at tksoft dot com>
- Date: Sat, 22 Apr 2000 15:42:46 -0700 (PDT)
- Cc: kaz at ashi dot footprints dot net
- Reply-To: glibc-linux at ricardo dot ecn dot wfu dot edu
>
> 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.
You meant to say:
strcat( target ,"\0" );
Also, strcat needs to calculate the length of the string again.
Better to use:
*(target+len) = '\0';
Nitpicking, I know, but I had to comment.
Troy