wrote:
> Salut Emmanuel!
>
> Thank you for your clear explanation!
>
> I have only one question; if I need to do a realloc in a function,
> won't this cost a lot in performance?
>
>
> Regards
> Dirk
Hi Dirk,
The problem is, your destination string is larger then your source string.
So, you need to realloc/malloc if you want to maintain the prototype you
specified. However, you can take the approach to make the situation a
little better where you allocate the maximum chunk of memory to build the
full HTML upfront. Then, use the following function to modify it in-place.
I have modified the prototype a little and you don't need to define HTMLi
HTMLb indipendently. For example the following program...
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#define BOLD "b"
#define ITALICS "i"
int HTMLx(char *str,int max_size, char *type)
{
int prefix_len;
int orig_len;
prefix_len = strlen(type) + 2;
orig_len = strlen(str);
if (max_size < (prefix_len+1)*2)
return -1; /* Failure... not enough space */
memmove(str+prefix_len,str,orig_len+1);
/* Build the prefix */
str[0]='<';
memcpy(str+1,type,strlen(type));
str[prefix_len - 1]='>';
/* Build the suffix */
str[prefix_len + orig_len] = '<';
str[prefix_len + orig_len + 1] = '/';
memcpy(str+prefix_len+orig_len+2,type,strlen(type) );
str[prefix_len + orig_len + strlen(type) + 2] = '>';
}
int main()
{
char *str = malloc(1000);
sprintf(str,"Hello Worldie");
HTMLx(str,1000,ITALICS);
printf("%s\n",str);
HTMLx(str,1000,BOLD);
printf("%s\n",str);
return 0;
}
Will give you output of :
<i>Hello Worldie</i>
<b><i>Hello Worldie</i></b>
Also, you can make it more robust where, when you run out of memory, it
reallocs another chunk. That will improve performance in terms of using
reduced number of reallocs.
Hope that helps.
- IG