Deeven Deeven - 2 months ago 13
C Question

String Array implementation is returning segmentation fault

int main(void)
{
const char* line = "This isn't working";
char* str[10];
int index = 0;

for(int i = 0; i < 10; i++)
{

int j = 0;
str[i] = malloc(10 * sizeof(char));
while(line[index] != ' ')
{

str[i][j] = line[index];
j++;
index++;
}
index++;
if(index == strlen(line) - 1)
break;


}

for(int i = 0; i < 10; i++)
{

printf("%s\n", str[i]);
}



}


I am trying to create a string array where I want to store words from my variable "line". But the code I've written is giving "segmentation fault" please help

Answer

On the sample string "This isn't working" your while(line[index] != ' ') will work forever. Length check is done only once, after this loop. Because of it you've got undefined behavior. It can be a main reason of your problem. Good article on this topic "Undefined behavior can result in time travel".

To fix it change while loop condition to:

int strLength = strlen(line);
while (index < strLength && line[index] != ' ')
{
  // Do the job here
}
Comments