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?


"tjk@tksoft.com" wrote:

> > len = strnlen( buffer );
> > target = ( char * )malloc( (len+1)*sizeof( char ) );
> > strncpy( target, buffer, len );

I don't understand two things:
First, is strnlen() just a typo? If not, I understand it as to return the length, if it is less or equal to a maximum and to return the maximum otherwise, but there would be the maximum parameter
missing. In the following I suppose it is meant to be strlen(buffer).

Second, doesn't the strncpy() make more comparisons than needed. I do the job nearly always this way:

tmpInt = strlen(buffer) + 1;
target = new char[tmpInt]; // target = malloc(tmpInt);
memcpy(target, buffer, tmpInt);

Is there any disadvantage of this code?

Servus,
Jörg
Müller-Tolk
_________________________________________________________
             ,
    ________/_    Joerg Mueller-Tolk    Muehlenweg 10
    _ __ __/ / ,' joerg@mueller-tolk.de 85653 Aying
_ / /  /  / /,'__________________________________________
 / /  /  / /'.    Mobile: 0177 8095711  Fax:  08095 2282
 \________/   '.  Office: 08102 740-167 Home: 08095 448
______________________________may_the_source_be_with_you_



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