3つの問題がありますが、それらは本質的に同じだと思います。C - 3文字列を返そうとしたときのセグメンテーションフォールトの問題
私は、パラメータとして取得する文字列上で何かをしている3つの関数を持っていますが、結果を返そうとすると、毎回セグメンテーションフォルトが発生し、なぜ理解できません。
/* 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;
}
と、この機能は付き文字列だけです私のプログラムからラベルを取得します ':' 文字を最後に:
/* 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;
}
と:関数内
/* 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;
}
を否定する必要がありますか? – Bathsheba
最初の文字列はありません。それは割り当てられておらず、ただNULLポインタです。残りの部分を調べるのは怠惰ですが、明らかにポインタを使って作業することについて知っていることを修正する必要があります。 –
'char * trimStr = NULL; ... strncpy(trimStr、str、i-1); ' - >無効な場所にデータを書き込もうとしています。 – chux