So my brother was making a program to turn all words in a string to hashtag, but for some reason it always gives a “segmentation fault” error at the end of execution. I tried to find what may cause it, but haven’t found. Here’s the code:
#include <stdio.h>
#include <string.h>
char* setHashtag(char text[10000])
{
int i, j;
printf("Initial text = %s\n", text);
for (i = 9998; i >= 0; i--)
{
text[i+1] = text[i];
}
text[0] = ' ';
for (i = 0; text[i+1] != '\0'; i++)
{
if(text[i] == ' ' && text[i+1] != ' ')
{
for (j = 9998; j > i; j--)
{
text[j+1] = text[j];
}
text[i+1] = '#';
printf("Partial text = %s\n", text);
}
}
return text;
}
void execute() {
char text[5000], textFinal[10000];
gets(text);
strcpy(textFinal, setHashtag(text));
printf("%s\n", textFinal);
}
int main()
{
execute();
printf("Back to main\n");
return 0;
}
You pass an array of size
5000into your function, yet you access10000elements inside. Of course, it will crash.This size of the array specified in function declaration does not matter. It is ignored by the compiler. This
is equivalent to this
i.e. the function receives a pointer to the beginning of your original argument array, not a new local copy of the argument array (naked arrays in C are not copyable).
This means that when you call your function as
the
textarray does not magically become achar [10000]array. It remains achar [5000]array, as it was originally declared. Attempting to accesstext[9998]and such inside the function leads to undefined behavior.Since your
setHashtagfunction expects a fixed size array of size10000, it might be a better idea to declare your function asand pass in the array arguments as
setHashing(&text). This will make sure you will not be able to pass in an array of wrong size. Inside the function you’ll have to access the array as(*text)[i].