【发布时间】:2016-10-03 18:20:45
【问题描述】:
我有这个程序,它接收一个 char 数组,其中包含许多由标签限制的消息。这些“标签”是随机位于字符数组中的字符序列。
这里是一个例子:给定一个字符数组:{'a','s','t','1','m','s','g','e','x','1','r','s','t','1','s','t','1','s','s','g','e','x','1','z'};。标签"st1" 表示消息的开头,包含每个字符,直到找到"ex1" 的序列,这是消息结束的标签,它不断在数组中搜索下一个“st1”序列表示新消息的开始。在本例中,消息为:"msg",和"st1ssg"。
这是我的程序 - 我不断收到分段错误:
int main(int argc, char const *argv[])
{
char array[] = {'a','s','t','1','m','s','g','e','x','1','r','s','t','1','s','t','1','s','s','g','e','x','1','z'};
int state = 0;
int found = 0;
int i,j;
int msgStartIndex;
int msgEndIndex;
while(array[i]){
if((array[i] == 's' && state == 0) || (array[i] == 't' && state == 1) || (array[i] == '1' && state == 2) ){
state++;
if(!found && state == 3){
msgStartIndex = i+1;
found = 1;
}
}
else if(!found && (array[i] = 't' && state == 2))
state = 2;
else if(!found)
state = 0;
if((array[i] == 'e' && state == 3) || (array[i] == 'x' && state == 2) || (array[i] == '1' && state == 1) ){
state--;
if(found && state == 0){
found = 0;
msgEndIndex = i-3;
for(j=msgStartIndex; j < msgEndIndex+1; j++)
printf("%c",array[j]);
printf("\n");
}
}
else if(found && (array[i] == 'e' ) && (state == 2 || state == 1))
state = 2;
else if(found)
state = 3;
i++;
}
return 0;
}
【问题讨论】:
-
if(!found && (array[i] = 't' && state == 2))这个条件违反了EXP45-C. Do not perform assignments in selection statements - CERT C Coding Standard - CERT Secure Coding Standards
标签: c arrays loops char segmentation-fault