1 pièce(s) jointe(s)
probleme d'allocation de texte
Bonjour a tous.
J'ai déjà pas mal utilisé les fonctions d'allocations, malloc, calloc et free. Par contre j'ai jamais utilisé realloc mais logiquement on doit pouvoir s'en sortir avec un free et un malloc non ?
En tout cas, j'ai un probleme dans mon code, je comprends vraiment pas, je marque deux fois la meme chose, juste que la deuxieme fois je passe par une fonction, et là j'ai un gros soucis.
Le code C est en piece jointe.
Le resultat a la console donne :
Citation:
stralloc: "un premier texte"
stralloc: "un texte modifie manuellement"
stralloc: "un premier texte"
realloc: ""
Merci de votre aide
Edit de gruik : je copie colle car le code est pas long
Code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51
| #include<stdio.h>
#include<stdlib.h>
char * stralloc (const char * str)
{
int i,n_char;
char * s;
for(n_char=0;str[n_char] != '\0';n_char++);
s= malloc((n_char+1)*sizeof(char));
for(i=0;i<n_char;i++)
s[i] = str[i];
s[n_char]='\0';
return s;
}
void strrealloc (char * str_dest, const char * str_src)
{
if(str_dest != NULL)
{
free(str_dest);
str_dest = NULL;
}
str_dest=stralloc(str_src);
}
int main(void)
{
char * str = NULL;
str = stralloc ("un premier texte");
printf("stralloc: \"%s\"\n",str);
if(str != NULL)
{
free(str);
str=NULL;
}
str=stralloc("un texte modifie manuellement");
printf("stralloc: \"%s\"\n",str);
free(str);
str = NULL;
str = stralloc ("un premier texte");
printf("stralloc: \"%s\"\n",str);
strrealloc(str,"texte modifier avec realloc");
printf("realloc: \"%s\"\n",str);
return EXIT_SUCCESS;
} |