codice:
#include <stdio.h>
#include <string.h>
#include <malloc.h>
int addspaces(char * dst, const char * src, int len);
int main(void)
{
char str1[] = "Ciao!";
char str2[] = "Come stai?";
int tlen;
if (strlen(str1) > strlen(str2))
{
tlen = strlen(str1);
}
else
{
tlen = strlen(str2);
}
tlen += 1; /* QUI! */
char * dest1 = (char *) malloc(tlen * sizeof(char));
char * dest2 = (char *) malloc(tlen * sizeof(char));
if (!dest1 || !dest2)
{
printf("Errore nell'allocazione o.O\n\n");
return 1;
}
if (!addspaces(dest1, str1, tlen) || !addspaces(dest2, str2, tlen))
{
printf("Errore nell'aggiunta degli spazi o.O o.O\n\n");
free(dest1);
free(dest2);
return 2;
}
printf("%s Ciao a te!\n", dest1);
printf("%s Bene!\n\n", dest2);
free(dest1);
free(dest2);
return 0;
}
int addspaces(char * dst, const char * src, int len)
{
if (strlen(src) > len)
{
strncpy(dst, src, len);
return 0;
}
if (strlen(src) == len)
{
strcpy(dst, src);
return 2;
}
int spaces = len - strlen(src);
int i;
for (i = 0; i < spaces; i++)
{
dst[i] = ' ';
}
strncpy(&dst[i], src, len);
return 1;
}
Il programma dovrebbe rendere le stringhe di lunghezza "len".
Se passo come parametro la lunghezza della stringa più lunga tutto ok, se invece aumento la lunghezza di uno ("tlen += 1;"), per aggiungere praticamente uno spazio in più davanti a entrambe le stringhe, allora il programma stampa correttamente le stringhe e poi appare il classico messaggio di crash, la solita finestrella di Windows "Il programma ha smesso di funzionare".
Mi sembra strano dato che comunque le stringhe le stampa .-.
Dove sbaglio?
EDIT: l'errore sembra essere causato dal 2° free... Ma perché??