0

dear all,

I have a problem at the following code that causes a segmentation fault and don't know the reason:

char * cString (char letter, char * string)
{
	char *first= string;
	char *point= string;

	while(*string!='\0')
	{
		if (*string!=letter)
		{
			*point=*string; //segmentation error
			point++;
		}
		string++;
	}
	return first;
}

I appreciate any help concerning this problem
Thanks a lot,

2
Contributors
4
Replies
5
Views
8 Years
Discussion Span
Last Post by Simzz
0

How are you calling that function?

This is how i call the function:
char * answer= cString('e',"Hello");

1

This is how i call the function:

char * answer= cString('e',"Hello");

That is your problem then. :) String constants are read only. Trying to modify one through a pointer to non-const char will likely throw an access violation. If you plan to pass string constants to a function, it is best to make those pointers point to const data:

char const* cString (char letter, char const* string)

And if the function is designed to modify one of the strings passed, make sure it is not pointing to const data, and be careful to make copies of string constants first:

char * cString (char letter, char * string)
char source[] = "Hello";
char * answer= cString('e', source);
Votes + Comments
nice solve ;)
This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.