C++ - Passing Pointer Into Function - c++

I keep on receiving odd unexpected values for my bool testValue. I keep receiving random numbers as I believe it is trying to access another region of memory. I predict it is how my code is setup within my testNumber() function, but I am unsure of how to solve it. This is my logic.
I have set ok to true. Now I assign the memory address of ok to pOk.
void TextBox::lengthTest(bool *pOk, int length) {
bool ok;
if (length < MAX_LENGTH) {
ok = true;
pOk = &ok;
} else {
ok = false;
pOk = &ok;
}
}
bool lengthTestBool = lengthTest(*pOk, length);
cout << lengthTestBool <<;
output:
85

You have a fundamental misunderstanding of how one uses pointers to implement reference semantics. You want to change thing that is pointed to by the pointer:
*pOK = ok;
However, C++ actually supports references semantics natively through reference types, which may be preferable:
void testNumber(bool & OK, int n)
{
OK = true;
// ...
}
Even better, though, is to simply return a bool:
bool testNumber(int n) { /* ... */ }
if (testNumber(x)) //... etc.

Related

Avoid stack corruption while writing to a pointer location

Let's assume that, we have a C API exposed by a C++ library where the C client queries a value by passing a void pointer and a key.
bool GetValue(const char* key, void* val) {
if(val != NULL) {
// find the value using the key with some logic of library
// lets assume found value is a int
int foundValue = 34;
*(int*)val = foundValue;
return true; // or false if key not found
}
return false;
}
The C client and the C++ library developers have an agreement about the size of values associated with keys.
Let's assume the C++ library only has int and long long int, and the C client also knows it.
So the C client is expected to behave as follows when the value associated with "some_key" is an int:
int valueHolder;
if(GetValue("some_key",&valueHolder)) {
// do something with valueHolder
}
But the C client can cause stack memory corruption by providing pointer which points to less space. For example, if the C client provides a pointer which points to an unsigned char and the value written by the C++ library is int, stack memory corruption can happen.
So the C client should take proper action to avoid such a situation. My question is, how the C++ library can handle such memory corruption/crash situation and be robust to crash or memory corruption? (a small note: a template or function overload is not an option for me because C++ library can not expose such feature to a C client).
Simply you have to design API in such way that type of the value is clear.
So for example:
bool GetIntValue(const char* key, int* val) {
if(val != NULL && IsIntValue(key)) {
// find the value using the key with some logic of library
// lets assume found value is a int
int foundValue = 34;
val = foundValue;
return true;
}
return false;
}
bool GetSizeValue(const char* key, size_t* val) {
if(val != NULL && IsSizeValue(key)) {
// find the value using the key with some logic of library
// lets assume found value is a int
size_t foundValue = 12;
val = foundValue;
return true;
}
return false;
}
...
Or other way:
enum Types {
Int,
Size,
....
};
struct Variant {
enum Types type;
union {
int integer;
size_t size;
....
};
};
bool GetVariantValue(const char* key, struct Variant* val) {
if(val != NULL) {
...
*val = MakeIntVariant(33);
return true;
}
return false;
}
Unfortunately it cannot be made robust, see this link:
Checking if a pointer is allocated memory or not
You can catch the crash however using something like
try {} catch (...) {}
but there is no guarantee it will crash, and in fact it is very likely to instead overwrite/corrupt adjacent memory.

Check any structure members for 0

I have a structure that contains x amount of integers, It is required that every last one of them be non-zero. Here's my structure:
struct thingy_t{
int a, b, c /* and so on */;
bool init();
};
Over time I will be adding many other members to the structure, which makes it an issue if I forget to check if it's non-zero. That's why I wanted to automate it for every member.
In my init function, it attempts to get values for the members, and return false if any of them are 0.
So far I have this:
bool thingy_t::init(){
a = GetValue(/* blah blah */); // Will return 0 if it can't find anything
b = GetValue(/* other blah */);
/* and so on */
// Check if any value is zero
for(int* i = (int*)this
; i < (int*)((char*)this + sizeof(interfaces_t))
; i++){
if(!*i) return false;
}
return true;
}
I am looking for a better way of doing this that would be more readable and more memory safe, as I am playing with fire(pointers) in a way they probably aren't intended.
Also, sorry for the for loop, I tried to make it more readable by wrapping it, but I probably made it worse.
There isn't a natural way to iterate over the struct and check for certain values of the members you have, so the better option for you, in my opinion, should be either make a better design for your task or make sure that you check for incorrect values on each access to that struct.
I'd simple implement the type to contain an array of int or (possibly better) a standard container.
If the number of values is specified at compile time ....
struct thingy_t
{
int x[number];
bool all_non_zero() const;
};
bool thingy_t::all_non_zero() const
{
for (int i = 0; i < number; ++i)
if (!number[i]) return false;
return true;
}
If the number is not specified at compile time, I'd use a standard container
struct thingy_t
{
std::vector<int> x;
thingy_t(std::size_t size) : x(size) {};
bool all_non_zero() const;
};
bool thingy_t::all_non_zero() const
{
for (std::vector<int>::const_iterator it = x.begin(), end = x.end();
it != end number; ++it)
if (!(*it)) return false;
return true;
}
The above works for all versions of C++, but may be simplified in C++11 or later.
bool thingy_t::all_non_zero() const
{
for (const auto &element : x)
if (!element) return false;
return true;
}
Naturally, you will need other functions to actually store values in the array or vector.
The code won't change if the number of integers changes. You will need to somehow track separately the meaning of each element.
I solved my own question while enjoying a nice breakfast.
Here's how I solved it:
struct thingy_t{
union{
struct{
int a, b, c;
}
int arr[3];
}
}
That way I can access variables via. their name and also their index in an array so I can check if each value is non-zero easier (creds: James Root for the array inspiration)

Dynamic Polymorphic Memory Container - Return Value Incorrect

I am currently working on an dynamic memory container.
Basic idea of the class is that you should be able to get the iterator of an object if you really do not know it, without the use of a for loop throughout all the elements to boost performance. The issue I have is the following; when you pass your pointer address to the object you want to get the iterator of it type casts the object into the extended memory containers structures type. This type contains an extra element, an integer. (IteratorNum)
When following the code the integer within the function is set to correct value, as below would be 50. But when the returned value is set into the local integer used in the main function it is 200? I've been adding watches and cannot figure out how it is possible that the function returns 50 but value gets set to 200.
template <typename DataType> class MemoryContainer {
public:
struct LevelData : DataType
{
int element;
};
DataType &New()
{
elements++;
//Reallocate the size of the array
ld = (LevelData*)realloc(ld, sizeof(LevelData) * elements);
//Set the iteratorNumber
ld[elements - 1].element = elements - 1;
return ld[elements - 1];
}
DataType *reserve(int num)
{
return calloc(num, sizeof(DataType));
}
DataType &operator[](int i)
{
return ld[i];
}
bool inArray(DataType *type)
{
//Compare memory addresses and see if it's within.
return (type >= &ld[0]) && (type < &ld[elements - 1]);
}
static unsigned int getIterator(DataType *type)
{
// v this is 50, but in main says returns 200.
return ((LevelData*)type)->element;
}
MemoryContainer()
{
elements = 0;
}
~MemoryContainer()
{
free(data);
}
private:
unsigned int elements;
LevelData *ld;
};
struct Effective
{
//Set it to polymorphic classes
virtual void dummy()
{
}
char * testvar;
Effective(char * c)
{
testvar = c;
}
Effective(){}
};
MemoryContainer<Effective> myContainer;
int _tmain(int argc, _TCHAR* argv[])
{
//Create 200 elements in the array
for(int i = 0; i < 200; i++)
myContainer.New().testvar = "E";
//Add pointer for testing purposes to get the iterator.
Effective * pointer = &myContainer[50];
//Test setting it's value
pointer->testvar = "HEHEHE";
//Get iterator of our pointer in the array
unsigned int i = myContainer.getIterator(pointer);
printf(pointer->testvar);
system("PAUSE");
return 0;
}
I suspect it is the visual studio debugger getting confused between your two i variables. If you print out the value of i, it will print correctly. If you change the name of your variable to something else, the value shows as 50 in the debugger.
That said, your code is a mish-mash of c and c++ and won't work correctly with anything that requires a copy constructor. I would suggest at the very least using new [] rather than realloc.
Also, any user of this collection who tries to store a class with a member variable called element is going to get mighty confused.
The unsigned int i in the main function really has a value of 50, but the debugger is confusing it with the i declared in the for loop (I reproduced this with Visual Studio 2013). If you cout i it will be 50, and if you change the variable name it will show up as 50 in the debugger. I've never seen this problem before so I wonder if it might be due to your use of malloc/realloc/free with C++ objects.

c++ - test a pointer

I am writting a method returning a double*. However, I would like to base another method behavior on output from this method. I would like to have
if (methodReturningArray()==0)
{
this_behavior();
}
else
{
this_other_behavior(methodReturningArray());
}
Is it appropriate then to have methodReturningArray() returning either the 'initialized' or 'build' double* and if this double* could not be appropriately be initialized or build, returning like that
double* new_array ;
return new_array ;
?
In other words, the double* output plays also role of a boolean to check whether some property is completed so that the double* output can be built.
Thanks and regards.
To indicate that something that you return by pointer has not been initialized, use return NULL. And check for it with if(double* d = method()) (or in any other fashion you like).
However, this is not your (or my) grandfathers C++ and you should only write something like this, when you absolutely have reason to do so. I would prefer to return either a std::array or std::vector by value wrapped and throw an exception if the behavior that leads to initialization failure is somehow exceptional. If failing to initialize is part of the idea I'd wrap the return value in a boost::optional. But probably I'd write something that takes an OutputIterator to not force any particular container on my client.
Notes on disaster: double* d; return d will leave your client with a pointer that points to random memory. There is no way for her to figure out if has to be deleted[] or if it is valid. Always initialize your pointers.
Code snippets:
// outputiterator
template<typename OutputIterator>
void myFunc(OutputIterator o) {
// fill stuff in
if(someThing) {
for(int i = 0; i < 5; ++i)
{
*o++ = 23;
}
} else {
// leave it empty
}
}
// client calls like:
std::vector<double> v;
myFunc(std::back_inserter(v));
if(!v.empty()) {
} else {
}
// exception
std::vector<double> myFunc() {
std::vector<double> v;
if(someThing) { v.push_back(23); return v; }
else throw std::runtime_error("Nargh!");
}
// client
try {
auto v = myFunc();
} catch(std::runtime_error err) {
}
// optional
boost::optional<std::vector<double>>
myFunc() {
std::vector<double> v;
if(someThing) { v.push_back(23); return v; }
else return boost::optional< std::vector<double> >();
}
//client
auto v = myFunc();
if(v) {
} else {
}
You got three ways, basically.
1) On error, return NULL. Then you can do boolean checks without issue, and it's sufficient in very most of cases.
2) Return boolean, and handle the double* output using a reference or a pointer argument like this:
bool methodReturningArray(double **out) { *out = ...; return true; }
double *out;
if (!methodReturningArray(&out)) this_other_behavior(out); else ....
3) Throw an exception - IMO kinda convoluted and unuseful.
Returning uninitialized pointer won't allow you to do boolean evaluation on it, and it's dangerous, as such pointer will be assumed dangling pointer afterwards.

C++ null string

I have a function in a C++ program returning a string.
On certain conditions, e.g. if the function encounters an error or so, I want to return a special value telling the caller that something has gone wrong.
I could basically just return an empty string "", but the function does need the empty string as normal return value.
How can I accomplish this?
Do I have do create a special data structure that for my function that holds a bool if the function was successfully run and a string containing the actual return value?
This sounds like a usecase for exceptions.
try {
std::string s = compute();
} catch(ComputeError &e) {
std::cerr << "gone wrong: " << e.what();
}
If you don't want to or can't use exceptions, you could change the function's interface
std::string result;
if(!compute(result)) {
std::cerr << "Error happened!\n";
}
Though most often, i've seen the return value is used for the actual result, and an error pointer is passed
bool b;
std::string s = compute(&b);
if(!b) {
std::cerr << "Error happened!\n";
}
This has the benefit that you can default the error argument pointer to 0 and code that can ignore the error (because it could live with an empty string return, for example, or if it knows in advance the input is valid) would not need to bother:
std::string compute(bool *ok = 0) {
// ... try to compute
// in case of errors...
if(ok) {
*ok = false;
return "";
}
// if it goes fine
if(ok) {
*ok = true;
}
return ...;
}
You can definitely return a pair, although it is klunky.
pair< string, bool > my_method(...) {
if (a) {
return make_pair(some_value, true);
} else {
return make_pair("", false); // error
}
}
pair< string, bool > result = my_method(...);
if (result.second) {
// success
} else {
// error
}
You can also pass either the bool or the string by reference,
bool my_method(string& s, ...) {
...
}
string s;
if (my_method(s, ...)) {
// success
} else {
// error
}
or:
string my_method(bool& ok, ...) {
ok = false; // default
...
}
bool ok;
s = my_method(ok, ...));
if (ok) {
// success
} else {
// error
}
You could try returning an auto_ptr to a string, but this will cost you an explicit new-ing of a string.
std::auto_ptr<std::string> Foo(int i)
{
if(i == 0) // Error!
return std::auto_ptr<std::string>(NULL);
else // Works.
return std::auto_ptr<std::string>(new string("Hello world!"));
}
If it's really something like an error, you should throw an exception. But by reading your question I guess it's not an "exceptional behaviour"?
If that's the case, you have several non-perfect solutions :
Return a structure with the string and a boolean that tells if the function failed (a simple std::pair<> could be enough).
Make your function modify a string parameter provided by reference and return a boolean telling if the function failed.
Make your function a functor/object that have a state. That state would be (at least) a boolean giving the failure or success of the last function call -- that would then be a function call.
3 is IMO bad design, while 2 and 1 are unperfect compromise.
It depends on how is your program organized.
You may return an additional boolean signifying if the function succeeded. You may return a structure containing boolean and string. You may return a special string (not necessarily empty) which should represent the failure. You may throw an exception. You may set a global flag indicating an error (though I would not recommend it).
There must be lot of other methods to express function failure, too.
The std::pair<> method is good. Another alternative is to have the caller pass the output string in as a non-const reference, and have the function return true or false depending on if an error was encountered or not.
bool Foo(int i, std::string& result)
{
bool ret = false; // no error
// do stuff...
result = "blahbalhbalh";
return ret;
}