This is the mail archive of the glibc-linux@ricardo.ecn.wfu.edu 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?


> 
> 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




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