Exception

Aug 1, 2013 at 6:42pm

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
#include "iostream"
using namespace std;
 char *value = "Sandeep";

char* delValue(char* p_value,char alphabet)
{
	int placeholder = 0;
	int count = 0;
	while(p_value[count] != NULL)
	{
		if(placeholder)
		{
			p_value[count] = p_value[(count+placeholder)];
                        // Why we get exception here. this seems to be valid line
		}
		if(p_value[count]== alphabet)
		{
			placeholder++;
		}else{
			count++;
		}
	}
   return p_value;
}

int main()
{

	cout<<delValue(value,'e');
	return 0;
}


I am trying to remove 'e' from "Sandeep" in above program. But compiler is throwing un-handled exception at line
p_value[count] = p_value[(count+placeholder)];

can any one tell me why i got exception(logic might be wrong, but operation is valid).
Aug 1, 2013 at 6:46pm
This statement

char *value = "Sandeep";

is not correct. Should be

const char *value = "Sandeep";

String literals may not be changed neither in C++ nor in C.
Aug 1, 2013 at 6:48pm
At some point count+placeholder is greater than the size of the array, meaning you're trying to access memory that doesn't exist.
Vlad had the right answer
Last edited on Aug 1, 2013 at 8:40pm
Aug 1, 2013 at 6:49pm
vlad from moscow..

i have purposefully kept it non-const as i have to delete "ee" from "sandeep"

and also i have checked

p_value[1] = p_value[2] is valid statement
Aug 1, 2013 at 6:51pm
No you are wrong. Even you declare the pointer without const in any case you may not change string literals. The behaviour is undefined. So your code is principally incorrect.
Aug 1, 2013 at 7:00pm
vlad from moscow..

Yes you are correct.

1
2
3
4
5
char* swapValue(char* p_value,int val1, int val2)
{
	p_value[val1]=p_value[val2];
   return p_value;
}


i am getting same exception for the above function as well for "Sandeep".

Thanks for clarification..:)
Aug 1, 2013 at 7:17pm
Instead of the pointer to a string literal You could use an array. for example


char value[] = "Sandeep";
Topic archived. No new replies allowed.