Elements in array keep changing unintentionally [duplicate] - c++

This question already has answers here:
Returning local data from functions in C and C++ via pointer
(13 answers)
Closed 5 years ago.
So I have two arrays which hold players x, y and z co-ordinates, however each time I call them they change their values the first time they are printed to the console they display the correct result however subsequent prints to the screen yield very small numbers,
HisPosition = GetPlayerPosition(aPlayer);
std::cout << "TheirPos=" << std::dec << HisPosition[0] << std::endl;
std::cout << "TheirPos1=" << std::dec << HisPosition[0] << std::endl;
if(!isnan(HisPosition[0])){
std::cout << "TheirPos2=" << std::dec << HisPosition[0] << std::endl;
Example console output:
TheirPos=440
TheirPos1=1.7118e-037
TheirPos2=1.7118e-037
They are defined like so:
float* HisPosition;
And GetPlayerPosition:
float* GetPlayerPosition(DWORD dwBase)
{
float result [3];
DWORD aXPos = dwBase + 0x134;
DWORD aYPos = dwBase + 0x138;
DWORD aZPos = dwBase + 0x13C;
result[0] = Read<float>(aXPos);
result[1] = Read<float>(aYPos);
result[2] = Read<float>(aZPos);
return result;
}
aPlayer stands for the address in memory of the player I am trying to fetch the offsets are correct as on the first console print the position is correct.
I'm new to using arrays in C++ and would appreciate any guidance.

return result; returns a dangling pointer to local, stack-allocated array that gets vanished when goes out of scope.

Related

Disproving Determinism via c++ [duplicate]

This question already has answers here:
Two different values at the same memory address
(7 answers)
C/C++ changing the value of a const
(18 answers)
Closed 5 months ago.
friends.
Recently I experimented a bit a C++ constants.
The code is:
#include <iostream>
int main() {
const int c = 1;
const int* ptr = &c;
int* tmp = const_cast<int*>(ptr);
*tmp = 5;
std::cout << &c << " " << ptr << " " << tmp << "\n";
std::cout << c << " " << *ptr << " " << *tmp;
}
I have investigated assembly code at godbolt: https://godbolt.org/z/7e3o7bWrs
The assembly code seems like doing what I wrote, exactly moving address of c into tmp variable and changes variable at this address.
Can you please tell me, why there is could be two different values at the same addresses?
Thank you.

what is the difference betwee new int() and new int[] [duplicate]

This question already has answers here:
Difference between operator new() and operator new[]()?
(5 answers)
Closed 5 years ago.
int main()
{
int *y = new int(5);
cout << "y = " << y << " &y = " << &y << " *y = " << *y << endl;
int *p = new int[5];
cout << "p = " << p << " &p = " << &p << " *p =" << *p << endl;
}
one used [] and another one used (), what's the different and how it works? Can someone help to explain to me? Thanks!
int *y = new int(5)
This allocates a single int and sets its value to 5, then assigns y to point at the allocated int.
int *p = new int[5]
This allocates an array of 5 ints, whose values are initially undefined, then assigns p to point at the first int in the allocated array.
You output so many things in your std::cout but most of them don't matter.
try
std::cout << sizeof(int(5)) << " " << sizeof(int[5]) << "\n";
which will output
4 20
since int(5) means a single integer initialised with 5. So sizeof yields the size of an int.
On the other hand, int[5] is what you expect: an array of 5 integers, so sizeof yields 5*sizeof(int).
Two more remarks:
creating good old arrays with new definitely is something a beginner should refrain from. If you need dynamically sized indexable storage, use std::vector. There is no speed panalty.
refrain from using namespace std; simply type the std::, that makes the code more readable and clearly separates your stuff from library stuff.

Returning an array in C++ [duplicate]

This question already has answers here:
Can a local variable's memory be accessed outside its scope?
(20 answers)
Closed 7 years ago.
I'm trying to learn C++ and had a question about returning arrays in C++. I know that in this case perhaps Vector may be better and that there is no need for a getter method as the fields are visible within the same class but I'm trying to learn about memory management so I'll use them.
class Color {
double r;
double g;
double b;
public:
Color(int a, int aa, int aaa) {
r = a;
g = aa;
b = aaa;
}
bool operator==(const Color &other) {
double *otherCol = other.getter();
return otherCol[0] == r && otherCol[1] == g && otherCol[2] == b;
}
double* getter() const {
double second[3] = {r,g,b};
return second;
}
};
int main() {
Color col1(23, 54, 200);
Color col2(23, 54, 200);
cout << (col1 == col2) << endl;
return 0;
}
This code should print out a 1 if the RGB colors are the same and 0 otherwise. But it does not print a 1. To debug, I added the following lines (twice on purpose) right before the return statement in operator==:
cout << otherCol[0] << " " << otherCol[1] << " " << otherCol[2] << endl;
cout << otherCol[0] << " " << otherCol[1] << " " << otherCol[2] << endl;
Oddly enough, the results are different:
23 54 200
6.91368e-310 6.91368e-310 3.11046e-317
Can someone please tell me what causes this and what would be a reasonable remedy that does not rely on Vector or dynamic allocation of memory? Let's assume that we don't want to pass in an array into getter() to update.
In getter you are returning the address of a local variable which results in undefined behavior so you are getting random memory. If you return a pointer you have to do something like new the variable in the called function and delete it after the function returns.
Or you could make second a class member which would keep it from going out of scope.
You could also pass the array in as a parameter.

Printing struct value from a list using iterator [duplicate]

This question already has an answer here:
Error in Getting Value from Vector of Pairs
(1 answer)
Closed 7 years ago.
I am having trouble with printing values from my struct Pages. I am trying to print the value of segment in Pages from a list of pages. The assignSegments() method is assigning values to the variable segment. This is the error I am getting. ‘std::list::iterator’ has no member named ‘segment’
Here is the code I have so far. If you need more code from me just let me know.
Following code is in my main
Process child;
char c = 'A';
c = c+i;
child.letter = c;
assignSegments(child.childPages, child.letter, CreateRandomNumber());
for(list<Pages>::iterator iter = child.childPages.begin(); iter != child.childPages.end(); i++)
{
cout << *iter.segment << endl; // having trouble printing here
}
Here are my structs that I am using.
struct Pages
{
string segment;
char validBit;
int refByte;
Pages * pagePointer;
int* memoryPointer;
};
struct Process
{
char letter;
list<Pages> childPages;
};
I think cout << iter->segment << endl; is what you're looking for.
operator. has a higher precedence over operator*, so iter.segment will be evaluated first, obviously it's not what you want.
Reference for C++ Operator Precedence
you can change
cout << *iter.segment << endl;
to
cout << (*iter).segment << endl;
or just
cout << iter->segment << endl;

changing the location a pointer-to-pointer points to while maintaining the value of two other pointers

So, I have been trying to learn C++ and in the tutorial book that I am reading, I have gotten stuck on a problem of pointers-to-pointers. What I am trying to do change the pointer a pointer-to-pointer is pointing to without changing the value of the original pointer. Here's some code...
#include <iostream>
void testFunc(int **func_p_to_p) {
int *createdPointer = new int(10);
*func_p_to_p = createdPointer;
cout << **func_p_to_p << endl; //prints 10 as I expect
}
int main() {
int **main_p_to_p = NULL;
int *mainPointer = new int(5);
main_p_to_p = &mainPointer;
testFunc(main_p_to_p);
cout << **test << endl;//prints 10, I expect this...
cout << *mainPointer << endl; //prints 10 as well, I don't want that.
}
I asked a similar question about this earlier, here and I understand sort of what is going on. However, I can't seem to figure out how I would change where a pointer-to-pointer is pointing to without changing the original value. Could anyone explain how I would do this? Thanks.
In the line
*func_p_to_p = createdPointer;
you first follow your pointer-pointer to what it is pointing to: The address of int *mainPointer.
Next you assign a new value to this pointer, the value of createdPointer which is the address of new int(10).
So your mainPointer is now changed to target the same memory as createdPointer. Does this make any sense to you?
You can't do that. main_p_to_p points to mainPointer, so modifying *main_p_to_p modifies mainPointer, full stop.
You might be looking for this, though:
int main() {
int **main_p_to_p = NULL;
int *mainPointer = new int(5);
int *secondPointer = mainPointer;
main_p_to_p = &secondPointer;
// prints 5 5 5
cout << *mainPointer << " " << *secondPointer << " " << **main_p_to_p << std::endl;
testFunc(main_p_to_p);
// prints 5 10 10
cout << *mainPointer << " " << *secondPointer << " " << **main_p_to_p << std::endl;
}
Note that you don't need the main_p_to_p variable, but I left it in for consistency with the question.