taking input from function argument and then console input

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?
You are lucky it works either way.

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:

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
32
33
34
35
36
37
38
39
40
41
42
43
#include<iostream>
#include<string>
#include<conio.h>
using namespace std;

class str
{
private:
  string x;  // better to use a standard string container -- it manages memory for you
  
public:
  void setData(const char* 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.

Hope this helps.
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.
Topic archived. No new replies allowed.