user3418378
user3418378

Reputation:

segmentation fault in array search C

I have this program that receives a char array with a number of messages bounded by tags. These "tags" are a sequence of chars located randomly within the char array.

Here is an example: given a 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'};. the tag "st1" indicates the beginning of a message which contains every char until a sequence of "ex1" is found, which is a tag for the end of the message, and it keeps searching the array for the next sequence of "st1" indicating the beginning of a new message. In this example, the messages are: "msg",and"st1ssg".

Here is my program - I keep getting a segmentation fault:

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;
}

Upvotes: 0

Views: 50

Answers (2)

Vlad from Moscow
Vlad from Moscow

Reputation: 311146

Variable I was notr initialized and moreover the array is not zero-terminated.

int i,j;
/...
while(array[i]){

So the loop has undefined behavior.

You could keep a string in the array and use standard function strstr declared in header <string.h> to find the starting and ending tags.

Upvotes: 0

Marc B
Marc B

Reputation: 360882

You never bothered initializing your loop counter:

int i,j;

while(array[i]){

so you just start using whatever random garbage is in i to begin with. If that garbage happens to be bigger than the length of the array, boom goes your program.

Upvotes: 2

Related Questions