[Date Prev][Date Next] [Thread Prev][Thread Next] [Date Index] [Thread Index]

oftopic : c programing Q - wierd behvior?



Firstly, I want to thank anyone who is willing to contribute their
knowledge and time.

I got a programing exersize. Among other things we had to emplement a new
string class which supports certain functions.

One of them was to allow append on a string which dinamicly allocates the
new space required.

when i emplemnted it in the simple way (typedef char ** string_t) t looked
like this:

void  string_append( string_t  str, char  * word )
{
  *str = (char *) realloc (*str, strlen(*str) + strlen(word) + 1);
  strcat(*str, word); 
}

i then tried to improve on this by turning string_t into a struct with a
variable length to remove one strlen call.
it looked something like:

{
   str->string = 
       (char *) realloc (str->string, str->length + strlen(word) + 1;
   ...
}

only this time it ran about five times slower ?!? anyone knows whats the
chause of this behaviour?

BTW when i ran profile on both versions I got that in the new version most
functions took almost twice as much time (library unchanged functions)
when i havn't changed the flags on the compiler)
If it helps it was compiled using g++ (as a C++ program but C code - for
typechecking warnings) with flags: -Wall -pedantic -p -O2

thanx
Micha Feigin
michf@math.tau.ac.il


Reply to: