I've written a function which I want to replace all the spaces in a string with '-'. I get a Segmentation Fault when I run it. However, using gdb with a break point set in the function and stepping through it, it works fine.
Code:
#include <stdio.h>
int replace (char *cat);
main()
{
char *s1 = "The cat sat ";
printf("The string before replacement is: \n");
printf("%s\n", s1);
int n = replace(s1);
printf("Number of replaced spaces: %d\n", n);
printf("The string after replacement is: \n");
printf("%s\n", s1);
}
int replace (char *cat)
{
int length = strlen(cat);
int r = 0;
int i;
for (i=0; i < length; i++)
{
printf("cat[%d]: %c\n", i, cat[i]);
if (cat[i] == ' ')
{
cat[i]='-'; // results in Seg Fault (set break point at beginning of line)
r++;
}
}
return r;
}
Thanks in advance!