Reputation: 1736
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;
}
Upvotes: -1
Views: 187
Reputation: 320719
You pass an array of size 5000
into your function, yet you access 10000
elements 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
char* setHashtag(char text[10000])
is equivalent to this
char* setHashtag(char *text)
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
char text[5000];
...
setHashtag(text)
the text
array does not magically become a char [10000]
array. It remains a char [5000]
array, as it was originally declared. Attempting to access text[9998]
and such inside the function leads to undefined behavior.
Since your setHashtag
function expects a fixed size array of size 10000
, it might be a better idea to declare your function as
char* setHashtag(char (*text)[10000])
and 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]
.
Upvotes: 8