Fonction renvoyant une string
Bonjour, ce message fait suite au poste http://www.developpez.net/forums/sho...d.php?t=140630 où j'ai une fonction qui transforme ma chaine de caractères en majuscule :
Code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14
|
#include <ctype.h>
void strtoupper(char *s)
{
if (s)
{
while(*s)
{
*s = toupper(*s);
s++;
}
}
} |
maintenant, je désire que ma string s ne soit pas modifiée donc voici ce que j'ai fait :
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
|
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<ctype.h>
char * strtoupper(char * s)
{
/* converts the string s with all these chars in capital letter */
char * str=strdup(s);
printf("str = %s\n",str);
while(*str!='\0')
{
printf("*str = %c\n",*str);
*str=toupper(*str);
++str;
}
printf("str = %s\n",str);
return str;
}
int main()
{
char s1[]="c7H15-2abc";
char * s2=strtoupper(s1);
printf("s2 = %s\n",s2);
free(s2); s2=NULL;
return 0;
} |
mais là il y a un bug lors de mon free(s2). Pourtant après un strdup il faut faire un free non ?
Merci