[英]Unexpected output of strlen function
我試圖實現一個修改字符串的函數:
代碼如下:
test.h文件:
#ifndef header_file
#define header_file
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
char * findWord(char *, char *);
#endif
test.c文件:
#include"test.h"
char * findWord(char *array, char *action)
{
char testchar;
int count=0, i=0, j, start = 0, end, wordLength = 0, charCount =0, k=0;
char *temp = malloc(sizeof(char)*400);
char *word = malloc(sizeof(char)*30);
char *replaceString = malloc(sizeof(char)*80);
if(strcmp(action,"replace") == 0)
{
while((testchar = array[i]) != '\0')
{
if(testchar == ',')
{
start = i+1;
i++;
continue;
}
else if(testchar == ':')
{
end = i;
word[charCount] = '\0';
charCount = 0;
printf("Start is: %d \n", start);
for(j=0; j< strlen(array); j++)
{
if(j == start)
{
sprintf(replaceString, "%s%s%s", "replace_",word,"_ii");
printf("Replace String for word %s is %s.\n",word,replaceString);
strcat(temp,replaceString);
j = (j-1)+(strlen(word));
k= strlen(replaceString);
printf("The value of J is %d for word %s.\n",j,word);
}
else
{
temp[k++] = array[j];
}
}
temp[k] = '\0';
k=0;
printf(" Words %s is replaced. The new string is:\n", word);
printf("%s\n",temp);
memset(word,'0',30);
memset(temp,'0',400);
memset(replaceString,'0',80);
i++;
continue;
}
if(testchar != 'Y')
{
word[charCount] = testchar;
charCount++;
}
i++;
}
}
else if(strcmp(action,"MISSING") == 0)
{
}
else if(strcmp(action,"EMPTY") == 0)
{
}
else
printf("Something went wrong.\n");
free(temp);
free(word);
free(replaceString);
}
main.c文件:
#include"test.h"
int main()
{
char sc[] = "cn:Y,x509UniqueIdentifier:Y,pseudonym:Y,name:Y,l:Y,street:Y,state:Y,postalAddress:Y,postalCode:Y,telephoneNumber:Y,emailAddress:Y";
findWord(sc, "replace");
return 0;
}
預期的產出是:
Replace String for word cn is replace_cn_ii.
replace_cn_ii:Y,x509UniqueIdentifier:Y,pseudonym:Y,name:Y,l:Y,street:Y,state:Y,postalAddress:Y,postalCode:Y,telephoneNumber:Y,emailAddress:Y
。 。 。 10輸出。
但由於strlen()
意外行為,它給出了垃圾值。 strcat()
函數后的word值會自動更改。
我哪里錯了? 讓我知道這個問題以及如何解決它。
謝謝!
你在temp
上調用strcat()
,但temp
不包含有效的字符串。 這給出了未定義的行為。
您必須首先確保temp
有效,即將其設為空字符串:
*temp = '\0';
當然,您還必須確保分配成功。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.