I observed an issue while setting a value into a char* through first as function argument and then from console input, the program compiles but don't run (Procesor fault in borland compiler and some <program>.exe not running in devC++:
#include<iostream>
#include<conio.h>
using namespace std;
class str{
private:
char* x;
public:
void setData(char* dat){
x=dat;
}
void getValue(){
cout<<" user->Enter Some String ";
cin>>x;
}
void display(){
cout<<x;
}
};
int main(){
str s1;
s1.setData("India");
s1.display();
s1.getValue();
s1.display();
getch();
return 0;
}
However, the program runs perfectly if i reverse the order of function calls, i.e first getValue() and then setData(). Please answer, why this happens?
char* x is an uninitialized pointer -- meaning it points to some random place in memory.
When you getValue(), you are writing a string to some random place in memory. Assuming that works, your string is at least null-terminated.
When you display(), each character of the string is accessed until a '\0' is found -- and that null may not be found before you get to memory you are not allowed to access.
You must have a place to keep the data. Here's a revision:
#include<iostream>
#include<string>
#include<conio.h>
usingnamespace std;
class str
{
private:
string x; // better to use a standard string container -- it manages memory for you
public:
void setData(constchar* dat) // should be 'const' -- read why below
{
x=dat;
}
void getValue()
{
cout<<" user->Enter Some String ";
//cin>>x;
getline(cin,x);
}
void display()
{
cout<<x;
}
};
int main()
{
str s1;
s1.setData("India"); // "India" is a const char* -- non-mutable
s1.display();
s1.getValue();
s1.display();
getch();
return 0;
}
I'd be remiss if I didn't mention a design flaw. You should not be doing any I/O in your getters or setters. I/O belongs elsewhere. A better name for getData() would be "askUserForData()" or "inputData()" or something like that.
Dear duoas, thanks for your reply! But my real concern is not to have a rescue from this situation by using string.h but to know the reason why it happens? If i call s1.getValue( ) and then call s1.setData("India") the program works properly, and x will still be an uninitialized pointer.
If you place s1.setData("India") before getData, x will point to string literal which is often resides in readonly memory, making getValue extremely likely to crash.
If you call getValue first, it will write to random memory, making it just likely to crash. You got unlucky and crash did not happened.
It both cases it is wrong thing to do and should be avoided.