472,787 Members | 1,463 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 472,787 software developers and data experts.

How to test for valid variable reference ?

Is it possible for a function to test one of it's passed in variables
(reference to object) for validity?
I would like the displayString( string &obString) function to verify
that obString 1) exists 2) is a valid string object. calling any
methods of said object cause a seg fault if the object doesnt exist.
(code to follow)

#include <string>
#include <iostream>
#include <vector>
using namespace std;

string displayString( string &obString) {
cout << "The display string is " << obString << endl;
return( obString);
}

int main() {

vector<string> obStringList;
string obString;

obString = "test string";
obStringList.push_back( obString);

displayString( obStringList[0]);

displayString( obStringList[1]);

return( 0);
}

localhost cpptest # g++ -Wall main.cpp
localhost cpptest # ./a.out
The display string is test string
Segmentation fault
localhost cpptest #

Nov 22 '05 #1
13 9393
joenuts wrote:
Is it possible for a function to test one of it's passed in variables
(reference to object) for validity?
I would like the displayString( string &obString) function to verify
that obString 1) exists 2) is a valid string object. calling any
methods of said object cause a seg fault if the object doesnt exist.
(code to follow)


No, sorry.

john
Nov 22 '05 #2
joenuts wrote:
Is it possible for a function to test one of it's passed in variables
(reference to object) for validity?
I would like the displayString( string &obString) function to verify
that obString 1) exists 2) is a valid string object. calling any
methods of said object cause a seg fault if the object doesnt exist.
(code to follow)

#include <string>
#include <iostream>
#include <vector>
using namespace std;

string displayString( string &obString) {
cout << "The display string is " << obString << endl;
return( obString);
}

int main() {

vector<string> obStringList;
string obString;

obString = "test string";
obStringList.push_back( obString);

displayString( obStringList[0]);

displayString( obStringList[1]);
use obStringList.at( 1 ) instead, as it does bounds checking. It throws
out_of_range

return( 0);
}

localhost cpptest # g++ -Wall main.cpp
localhost cpptest # ./a.out
The display string is test string
Segmentation fault
localhost cpptest #

Nov 22 '05 #3
On 21 Nov 2005 14:28:54 -0800, "joenuts" <jo*****@gmail.com> wrote:
Is it possible for a function to test one of it's passed in variables
(reference to object) for validity?
I would like the displayString( string &obString) function to verify
that obString 1) exists 2) is a valid string object. calling any
methods of said object cause a seg fault if the object doesnt exist.
(code to follow)
References automatically guarantee that both (1) and (2) are true
INSIDE the function body, unless you have done something to make the
original object referenced become invalid. Your segfault comes from
trying to access the second element of your vector which has only one
element. The program never makes it to the function the second time
around.

If you use vector::at() instead of vector::operator[], you will get a
C++ exception (std::out_of_range). Indexing further into a vector than
there are elements with operator[] causes undefined behavior (i.e.
crashes).
#include <string>
#include <iostream>
#include <vector>
using namespace std;

string displayString( string &obString) {
cout << "The display string is " << obString << endl;
return( obString);
}

int main() {

vector<string> obStringList;
string obString;

obString = "test string";
obStringList.push_back( obString);

displayString( obStringList[0]);

displayString( obStringList[1]);

return( 0);
}

localhost cpptest # g++ -Wall main.cpp
localhost cpptest # ./a.out
The display string is test string
Segmentation fault
localhost cpptest #


--
Bob Hairgrove
No**********@Home.com
Nov 22 '05 #4
joenuts wrote:
Is it possible for a function to test one of it's passed in variables its (reference to object) for validity?
I would like the displayString( string &obString) function to verify
that obString 1) exists 2) is a valid string object. calling any
methods of said object cause a seg fault if the object doesnt exist.
(code to follow)
The problem here is not the string variable, it is the the fact that
you're referencing a vector element that doesn't exist (in this case
`obStringList[1]').

If you use the `at' member of the vector template, it will throw an
`out_of_range' exception, which you can catch.

Remember, references are *always* valid (as distinguished from pointers,
which may be NULL).

[see notes below]
#include <string>
#include <iostream>
#include <vector>
using namespace std;

string displayString( string &obString) {
cout << "The display string is " << obString << endl;
return( obString);
}

int main() {

vector<string> obStringList;
string obString;

obString = "test string";
obStringList.push_back( obString);

displayString( obStringList[0]);

displayString( obStringList[1]);
Whoops. There *is* no obStringList[1], yielding undefined behavior (in
this case a segmenetation fault). Your code never gets as far as the
second call to displayString().

If you instead used obStringList.at(1), you could wrap it in a try catch
block and recover from the exception. [Of course, you could first test
the index against the size of the vector.]
return( 0);
}

localhost cpptest # g++ -Wall main.cpp
localhost cpptest # ./a.out
The display string is test string
Segmentation fault
localhost cpptest #

HTH,
--ag

--
Artie Gold -- Austin, Texas
http://goldsays.blogspot.com
http://www.cafepress.com/goldsays
"If you have nothing to hide, you're not trying!"
Nov 22 '05 #5
joenuts wrote:
Is it possible for a function to test one of it's passed in variables
(reference to object) for validity?
I would like the displayString( string &obString) function to verify
that obString 1) exists 2) is a valid string object. calling any
methods of said object cause a seg fault if the object doesnt exist.
(code to follow)

#include <string>
#include <iostream>
#include <vector>
using namespace std;

string displayString( string &obString) {
cout << "The display string is " << obString << endl;
return( obString);
}

int main() {

vector<string> obStringList;
string obString;

obString = "test string";
obStringList.push_back( obString);

displayString( obStringList[0]);

displayString( obStringList[1]);

return( 0);
}

localhost cpptest # g++ -Wall main.cpp
localhost cpptest # ./a.out
The display string is test string
Segmentation fault
localhost cpptest #


The problem is in the call, not in the function. Inside the function is
where the program realizes the variable is invalid. Since you're passing
it by reference, it is the responsibility of the caller to ensure that
the arguments are proper, and since std::vector by default does not
throw errors on out of range access, you should check before calling if
there is a question.

Your displayString should always safely assume that a reference
parameter is valid. Use 'bool std::string::empty()' to see if it has
contents if necessary.

--Paul
Nov 22 '05 #6
On 21 Nov 2005 19:12:25 -0800, "joenuts" <jo*****@gmail.com> wrote:
Thanks all for the quick responses. I understand that it was the out of
bounds call that causes the segfault (essentially). For those who say
that the second function call never happens due to the out of bounds
call in the parameter list, consider the following code (attached ..
slightly modified from original code). *note* from what I can tell, the
function call DOES happen, and any line in the function that doesnt
contain the reference variable (and precedes it) runs correctly. It is
only when trying to execute the code that contains the variable
reference that the program crashes. (food for thought)


It's really irrelevant, because the minute you access the non-existant
vector element, you have "undefined behavior". That can mean anything,
from formatting your hard disks to executing the code in
displayString()seemingly correctly. You cannot prohibit ANYTHING once
there is undefined behavior, so you need to take care of it where it
occurs.

[rest snipped]

--
Bob Hairgrove
No**********@Home.com
Nov 23 '05 #7
> > string displayString( string &obString) {
cout << "The display string is " << obString << endl;
return( obString);
} Actually there is some chance to catch rough errors of calling code.
E.g. you can check that:
1) (&obString != 0) - case when somebody called displayString with
reference to string at address 0.
2) If you use debug build than on some platforms there can be some
"magic" pointer values which show you that pointer is invalid -
something like (&obString != 0xCDCDCD). However this is platform
specific - and can be not available.
3) Moreover you can look through std::string implementation and try to
check its internals - very nasty and not portable.

If you really want to do such a check you should develop some registry
of all strings in the program. You can try smart pointer with available
IsValid() method or something like this:
int displayString( int &obString) {
if (MyRegistry::StringIsValid(obString))
cout << "The display string is " << MyRegistry::GetString(obString) <<
endl;
return( obString);
}

However, as discussed, at this point nothing can help your program,
even this "smart pointer"/registry trick.displayString( obStringList[1]);


Nov 23 '05 #8
On 22 Nov 2005 03:38:30 -0800, "Dervish" <DA*******@yandex.ru> wrote:
> string displayString( string &obString) {
> cout << "The display string is " << obString << endl;
> return( obString);
> }Actually there is some chance to catch rough errors of calling code.
E.g. you can check that:
1) (&obString != 0) - case when somebody called displayString with
reference to string at address 0.
This is silly. The language prohibits that from happening. If the
compiler *does* let this through, then it's broken.
2) If you use debug build than on some platforms there can be some
"magic" pointer values which show you that pointer is invalid -
something like (&obString != 0xCDCDCD). However this is platform
specific - and can be not available.
But we aren't talking about pointers. We are talking about references.
Pointers are not references, and references are not pointers.
3) Moreover you can look through std::string implementation and try to
check its internals - very nasty and not portable.
Total waste of time. Besides, it has nothing to do with the question
which concerned "test for valid reference". A reference need not be a
reference to std::string, it could be a reference to anything ...
including a type defined in a closed-source third-party library to
which only the interface is available.
If you really want to do such a check you should develop some registry
of all strings in the program. You can try smart pointer with available
IsValid() method or something like this:
int displayString( int &obString) {
if (MyRegistry::StringIsValid(obString))
cout << "The display string is " << MyRegistry::GetString(obString) <<
endl;
return( obString);
}
Wouldn't work if strings can be generated from user input, would it?
And this is *really* unnecessary, and much more error-prone than just
using the simple reference.
However, as discussed, at this point nothing can help your program,
even this "smart pointer"/registry trick. >displayString( obStringList[1]);


Exactly. All the other suggestions are just smoke and mirrors to cover
up the real problem, which is undefined behavior caused by accessing
an element in the vector which doesn't exist.

--
Bob Hairgrove
No**********@Home.com
Nov 23 '05 #9
On Tue, 22 Nov 2005 13:31:11 +0100, Bob Hairgrove
<in*****@bigfoot.com> wrote:
On 22 Nov 2005 03:38:30 -0800, "Dervish" <DA*******@yandex.ru> wrote:
> string displayString( string &obString) {
> cout << "The display string is " << obString << endl;
> return( obString);
> }

Actually there is some chance to catch rough errors of calling code.
E.g. you can check that:
1) (&obString != 0) - case when somebody called displayString with
reference to string at address 0.


This is silly. The language prohibits that from happening. If the
compiler *does* let this through, then it's broken.


More precisely, you are probably worried about something like the
following (i.e. the dangling reference):

string * pStr = new string("Hello");
string& rStr = *pStr;
delete pStr;
pStr = 0;
// evil code:
displayString(rStr);

By the time you call "delete pStr;", rStr is an invalid reference.
*Any* use of rStr afterwards creates undefined behavior! And once you
have undefined behavior, the best checks in the world won't help you
revert to well-defined behavior inside of displayString(). It is
(remotely) possible that &rStr could be zero, but only because after
there is undefined behavior, anything is possible! It's a big trap to
think that you can write code to get out of undefined behavior once
you are in it.

But, since most people who like to write code comparing the address of
a reference to 0 also seem to believe that "references are just fancy
pointers" (they are not!), you will probably expect the following
internal implementation of the above as a pointer:

string * pStr = new string("Hello");
// implement rStr as a pointer:
string * rStr = pStr;
delete pStr;
pStr = 0; // What does rStr now point to??
// evil code:
// assuming that displayString() now expects a pointer:
displayString(rStr);

Obviously, rStr as a pointer will not compare equal to 0, either. You
are stuck with the same problem given the above situation. However,
with the pointer version, you MUST check the argument ANYWAY because
the language allows passing a null pointer to the function. That is
what the reference buys you.

--
Bob Hairgrove
No**********@Home.com
Nov 23 '05 #10
>Pointers are not references, and references are not pointers.
But it possible to convert one to another - and due to this (if design
of interfaces is poor) - bad thing can happen. Look:

#include <iostream>
using namespace std;

string displayString( string &obString) {
if ( &obString==0)
{
cout << "Bad thing happened" << endl;
return "Blablabla";
}
else
{
cout << "The display string is " << obString << endl;
}
return( obString);
}
int main(int, char**)
{
std::string hello("Hello, world!");
srand(time(0));
int canHappen = rand()%2;
std::string *ptr = canHappen?0:&hello;
displayString(*ptr);
return 0;
}
So check of reference can help - but usually it is a sign, that pointer
should be used instead of reference.
Wouldn't work if strings can be generated from user input, would it?

It would work. One can do something like this:
int obString = MyRegistry::ReadStringFromCin();

Nov 23 '05 #11

Dervish wrote:
Pointers are not references, and references are not pointers. But it possible to convert one to another - and due to this (if design
of interfaces is poor) - bad thing can happen. Look:

#include <iostream>
using namespace std;

string displayString( string &obString) {
if ( &obString==0)


It is impossible for this condition to be true unless you have already
invoked undefined behaviour, in which case anything you try and do from
that point on is irrelevant.
{
cout << "Bad thing happened" << endl;
return "Blablabla";
}
else
{
cout << "The display string is " << obString << endl;
}
return( obString);
}
int main(int, char**)
{
std::string hello("Hello, world!");
srand(time(0));
int canHappen = rand()%2;
std::string *ptr = canHappen?0:&hello;
displayString(*ptr);
Here you derefernce ptr. If canHappen is zero then ptr is null and
dereferencing it is undefined behaviour. What the displayString
function does or does not try to do about that is irrelevant.
return 0;
}
So check of reference can help - but usually it is a sign, that pointer
should be used instead of reference.


No it can't help, but yes if you want to be able to pass null then a
pointer should be used because there is no way to pass a null
reference.

Gavin Deane

Nov 23 '05 #12
"Bob Hairgrove" <in*****@bigfoot.com> wrote in message
news:vd********************************@4ax.com...
E.g. you can check that:
1) (&obString != 0) - case when somebody called displayString with
reference to string at address 0.


This is silly. The language prohibits that from happening. If the
compiler *does* let this through, then it's broken.


Really? Why do you think so?

Suppose I write the following:

#include <iostream>

void f(int& foo)
{
if (&foo == 0)
std::cout << "&foo is zero\n";
}

int main()
{
int* p = 0;

f(*p);
return 0;
}

I think you are saying that if I compile and execute this program and it
prints "&foo is zero", that means that my compiler is broken. If so, I
think you are mistaken: I think that if you compile and execute this
program, you cannot draw any inference at all about whether the compiler is
working correctly, regardless of what the program does when executed.

My reasoning is simple: p is a zero pointer, so the effect of evaluating *p
is undefined. So the moment the program has evaluated *p, the
implementation is free to do absoluately anything it wishes, and you cannot
claim it is broken regardless of what it does.

So if you are saying that only a broken compiler would print "&foo is zero"
when given the program above, I think you're mistaken. If you mean
something else, would you mind clarifying what it is?

Nov 23 '05 #13
On Tue, 22 Nov 2005 18:26:35 GMT, "Andrew Koenig" <ar*@acm.org> wrote:
"Bob Hairgrove" <in*****@bigfoot.com> wrote in message
news:vd********************************@4ax.com.. .
E.g. you can check that:
1) (&obString != 0) - case when somebody called displayString with
reference to string at address 0.
This is silly. The language prohibits that from happening. If the
compiler *does* let this through, then it's broken.


Really? Why do you think so?


I posted an additional message trying to be more specific, and I
believe we are in agreement, but I implied that the compiler might
somehow be an accomplice to undefined behavior, and that was wrong. By
"let that through", I meant that the language guarantees that the
address of objString can never be zero with well-defined behavior, so
checking it is useless.

Here's an instant replay, in case you hadn't seen it before your reply
came through: The C++ standard says that a reference must be
initialized with a valid object. OK, so as long as the lifetime of
that object, we have well-defined behavior WRT the reference (i.e
assuming nothing else causes UDB). When (and if) the code gets to the
body of displayString(), there are only two possibilities: (a)
behavior is still well-defined, and therefore obString must be a valid
reference; (b) something has happened to the referenced object
*before* the code gets to the body of displayString(), and the
reference isn't valid anymore. The instant we use that reference in
any way, we have undefined behavior (dangling reference).

My mistake was in choosing the wording "let that through". With UDB,
it is also possible, of course, that the compiler "lets that through".
As you say, that doesn't mean that the compiler is broken. My point
was that it is useless to try to prevent, or somehow recover from, UDB
by silly checks such as comparing the address of the referenced object
to 0.
Suppose I write the following:

#include <iostream>

void f(int& foo)
{
if (&foo == 0)
std::cout << "&foo is zero\n";
}

int main()
{
int* p = 0;

f(*p);
return 0;
}

I think you are saying that if I compile and execute this program and it
prints "&foo is zero", that means that my compiler is broken. If so, I
think you are mistaken: I think that if you compile and execute this
program, you cannot draw any inference at all about whether the compiler is
working correctly, regardless of what the program does when executed.
Yes! You have illustrated much better what I was trying to say.
My reasoning is simple: p is a zero pointer, so the effect of evaluating *p
is undefined. So the moment the program has evaluated *p, the
implementation is free to do absoluately anything it wishes, and you cannot
claim it is broken regardless of what it does.

So if you are saying that only a broken compiler would print "&foo is zero"
when given the program above, I think you're mistaken. If you mean
something else, would you mind clarifying what it is?


I am sorry that I implied something which cannot be the compiler's
fault. It is solely the programmer's fault. I keep forgetting that no
diagnostic is necessary for pograms that cause UDB (although that
would be really nice! <g>).

--
Bob Hairgrove
No**********@Home.com
Nov 23 '05 #14

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

12
by: HB | last post by:
After trying for days!! I need help: Is there any way I can refer to a variable with another variable. I.e.: I have many variables: var1 , var2 , var3 etc etc I want to use a loop to change...
2
by: James Marshall | last post by:
Does anyone know.... In JavaScript, is there any way to get a reference to a string variable (not an object), like Perl's "\" operator? I want to be able to compare two such references and know...
1
by: jm | last post by:
I have one form. It is named Form1. I have one class file named netclass.cs The form Form1 has one textbox named textBox1. All I want to do is reference textBox1.text in the netclass.cs...
1
by: Carlos | last post by:
Hi all, I do get the following exception when trying to create a new data row in one of my tables: System.Data.SqlClient.SqlException: Must declare the variable '@cAttend' I have the...
2
by: Friskusen | last post by:
Hello VB.net programmers ! I'm just trying to understand what happens with an object which is initialised over and over again. The code fragment below illustrates my problem. This code is...
6
by: depalau | last post by:
I'm running into some issues on maintaining a static variable across the lifetime of a web service and I was wondering if anyone could help. Background: We have developed a C#/1.1 web service...
3
by: christianlott1 | last post by:
I wouldn't have brought this up except that a friend had a similar problem as well. Situation: Code works fine for months, then suddenly breaks. In my case the code broke on a piece of...
1
by: josh | last post by:
Hi, I have an error when I try to make: CustomObj = { is_all : Compatible(), Types : { PASS : CustomObj.as_all ? "ok" : "onok", ...
0
by: Rina0 | last post by:
Cybersecurity engineering is a specialized field that focuses on the design, development, and implementation of systems, processes, and technologies that protect against cyber threats and...
3
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 2 August 2023 starting at 18:00 UK time (6PM UTC+1) and finishing at about 19:15 (7.15PM) The start time is equivalent to 19:00 (7PM) in Central...
0
by: erikbower65 | last post by:
Using CodiumAI's pr-agent is simple and powerful. Follow these steps: 1. Install CodiumAI CLI: Ensure Node.js is installed, then run 'npm install -g codiumai' in the terminal. 2. Connect to...
0
by: erikbower65 | last post by:
Here's a concise step-by-step guide for manually installing IntelliJ IDEA: 1. Download: Visit the official JetBrains website and download the IntelliJ IDEA Community or Ultimate edition based on...
0
by: kcodez | last post by:
As a H5 game development enthusiast, I recently wrote a very interesting little game - Toy Claw ((http://claw.kjeek.com/))。Here I will summarize and share the development experience here, and hope it...
14
DJRhino1175
by: DJRhino1175 | last post by:
When I run this code I get an error, its Run-time error# 424 Object required...This is my first attempt at doing something like this. I test the entire code and it worked until I added this - If...
0
by: lllomh | last post by:
Define the method first this.state = { buttonBackgroundColor: 'green', isBlinking: false, // A new status is added to identify whether the button is blinking or not } autoStart=()=>{
0
by: Mushico | last post by:
How to calculate date of retirement from date of birth
2
by: DJRhino | last post by:
Was curious if anyone else was having this same issue or not.... I was just Up/Down graded to windows 11 and now my access combo boxes are not acting right. With win 10 I could start typing...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.