Exception


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).
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.
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
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
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.
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..:)
Instead of the pointer to a string literal You could use an array. for example


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