J'ai 3 problèmes mais je pense qu'ils sont essentiellement les mêmes.C - 3 problèmes avec la segmentation faute quand essayer de retourner la chaîne
J'ai 3 fonctions qui font quelque chose sur la chaîne qu'ils obtiennent en tant que paramètre, mais quand j'essaye de renvoyer le résultat, j'obtiens une faute de segmentation à chaque fois et je ne peux pas comprendre pourquoi.
/* the function gets a string, and return the string without blank spaces (is exists) in the end of the string */
char *trimRightSpaces(char *str, unsigned int len)
{
unsigned int i = len;
char *trimStr = NULL;
if(str == NULL)
return NULL;
while(i > 0)
{
if(isspace((int)str[i]))
break;
i--;
}
strncpy(trimStr, str, i-1);
trimStr[i+1] = '\0';
return trimStr;
}
et cette fonction obtient des étiquettes de mon programme, qui ne sont que des chaînes avec caractère ':' à la fin:
/* The function gets a pointer to a string, and returns the name of label without ':' if it's a valid label, NULL if not. */
char *isLabel(char *str)
{
int i;
char tempStr[80];
if(str == NULL)
return NULL;
if(strlen(str) > VALID_LABEL_LENGTH)
return NULL;
for(i = 0; i < strlen(str); i++)
{
if(i == 0)
{
/* if the first letter of the string is not small or capital letter, then it's not a valid label. */
if(!isalpha((int)str[0]))
return NULL;
}
if(i == (strlen(str) - 1))
{
if((int)str[i] != ':') /* check it the word ends with ':', otherwise it's not a valid label */
return NULL;
break;
}
if(!isalnum((int)str[i]))
return NULL;
}
strncpy(tempStr, str, strlen(str) - 1);
if(isLanguageWord(tempStr))
return NULL;
return str;
}
et:
/* the function get a string, and check if it's a valid string: a string inside " ". if it's valid, it returns the string without " ", and NULL otherwise. */
char *validString(char *str)
{
char temp[80];
char *temp2 = NULL;
int i;
if(str == NULL)
return NULL;
if(str[0] != '"' || str[strlen(str) - 1] != '"')
return NULL;
for(i = 1; i < strlen(str) - 1; i++)
{
temp[i] = str[i];
}
temp2 = temp;
return temp2;
}
Où diantre est la mémoire allouée pour 'trimStr' dans votre premier extrait? – Bathsheba
Dans le premier, il n'y a pas de chaîne. Il n'est pas alloué, juste un pointeur NULL. Paresseux pour passer le reste, mais évidemment vous avez besoin de réviser ce que vous savez sur le travail avec des pointeurs. –
'char * trimStr = NULL; ... strncpy (trimStr, str, i-1); '-> Tenter d'écrire des données dans un emplacement invalide. – chux