Crashes when reading a member pointer of a structure from a function - c++

I have the following structure, class and function snippet:
structure:
struct myData
{
short index;
char name[32];
}
class:
class myFoo
{
...
public:
short count;
myData** data;
...
}
function:
int Do_Bar(myFoo vFoo)
{
...
myData* data = *vFoo.data;
for (short i=0; i<vFoo.count; ++i)
{
Printf("%3d %s", data.index, data.name);
}
...
}
function call:
...
myFoo foo;
SomeAPI_GetCompleteObjectList(&foo);
Do_Bar(foo);
...
But my code crashes with these code. But if I removed the parameter and create a myFoo class in Do_Bar() function instead, the code works fine:
int Do_Bar(myFoo vFoo)
{
myFoo foo;
SomeAPI_GetCompleteObjectList(&foo);
...
myData* data = *vFoo.data;
for (short i=0; i<vFoo.count; ++i)
{
Printf("%3d %s", data.index, data.name);
}
...
}
Why is it? And how to resolve this?
EDIT1:
I forgot to mention that the initializations of foo is done before the function call. This was initialized using an API.
I modified the code for this.

You have not given memory to pointer data in line myData* data and trying to assign something to it.Alternative method are either
define myData data then use &data as pointer
or allocate memory using dynamic memory allocation.

You have a couple of undefined behaviors in that little piece of code...
You have a double-pointer, but never "point" either of them to anything. This mean they will point to random memory locations.
You print an uninitialized character array, which means it contains random data.
And since you don't do any initialization at all, foo.count will also contain a random value, which may be negative or very large.
And last bot not least, like I said in my comment, that code should not even compile as you use the wrong syntax for the access of the members in the structure.

Related

Problem while initializing attribute in constructor c++

While i try to debug
ERROR appear :
"Unhandled exception at 0x5784F2F6 (ucrtbased.dll) in Final project.exe: An invalid parameter was passed to a function that considers invalid parameters fatal."
Tried every thing can't figure out how to solve this.
using namespace std;
class Map :
{
private:
double *mhours_played;
string *maps;
unsigned element_num;
public:
Map()
{
maps[2] = { "Summoner's rift", "Aram" };
element_num = 2; mhours_played[2] = {};
}
~Map() { delete[] maps; }
};
These statements
maps[2] = { "Summoner's rift", "Aram" };
mhours_played[2] = {};
do not make sense. maps and mhours_played are pointers that within the body of the constructor have indeterminate values. They are not arrays as you think. For example the expression maps[2] is a scalar object of the type std::string.
Define the constructor at least like
Map() : mhours_played( new double[2]() ),
maps( new std::string[2] { "Summoner's rift", "Aram" } ),
element_num( 2 )
{
}
and the destructor like
~Map()
{
delete[] maps;
delete[] mhours_played;
}
It seems like the key misunderstanding here is the difference between stack and heap allocation. Your code would be (almost) correct if we were normally allocating space for an array in a function:
#include <string>
int main() {
std::string maps[2] = {"Chad", "Zimbabwe"};
}
This is perfectly valid, and works as expected. However, what you're trying to do is dynamically allocate space for an array of strings in memory location maps. This syntax for this would be as follows:
#include <string>
int main() {
std::string* maps;
maps = new std::string[2];
// ... more code ...
// always free your memory!
delete[] maps;
}
This tells the OS, "hey! I want some memory for an array, can I have some?" and the OS (hopefully) says "yeah, here you go have fun."
Currently, your code tries to access the second index in unallocated memory, and the OS really doesn't like that.
I hope this helps, and let me know if you need further clarification.

Save reference to void pointer in a vector during loop iteration

Guys I have a function like this (this is given and should not be modified).
void readData(int &ID, void*&data, bool &mybool) {
if(mybool)
{
std::string a = "bla";
std::string* ptrToString = &a;
data = ptrToString;
}
else
{
int b = 9;
int* ptrToint = &b;
data = ptrToint;
}
}
So I want to use this function in a loop and save the returned function parameters in a vector (for each iteration).
To do so, I wrote the following struct:
template<typename T>
struct dataStruct {
int id;
T** data; //I first has void** data, but would not be better to
// have the type? instead of converting myData back
// to void* ?
bool mybool;
};
my main.cpp then look like this:
int main()
{
void* myData = nullptr;
std::vector<dataStruct> vec; // this line also doesn't compile. it need the typename
bool bb = false;
for(int id = 1 ; id < 5; id++) {
if (id%2) { bb = true; }
readData(id, myData, bb); //after this line myData point to a string
vec.push_back(id, &myData<?>); //how can I set the template param to be the type myData point to?
}
}
Or is there a better way to do that without template? I used c++11 (I can't use c++14)
The function that you say cannot be modified, i.e. readData() is the one that should alert you!
It causes Undefined Behavior, since the pointers are set to local variables, which means that when the function terminates, then these pointers will be dangling pointers.
Let us leave aside the shenanigans of the readData function for now under the assumption that it was just for the sake of the example (and does not produce UB in your real use case).
You cannot directly store values with different (static) types in a std::vector. Notably, dataStruct<int> and dataStruct<std::string> are completely unrelated types, you cannot store them in the same vector as-is.
Your problem boils down to "I have data that is given to me in a type-unsafe manner and want to eventually get type-safe access to it". The solution to this is to create a data structure that your type-unsafe data is parsed into. For example, it seems that you inteded for your example data to have structure in the sense that there are pairs of int and std::string (note that your id%2 is not doing that because the else is missing and the bool is never set to false again, but I guess you wanted it to alternate).
So let's turn that bunch of void* into structured data:
std::pair<int, std::string> readPair(int pairIndex)
{
void* ptr;
std::pair<int, std::string> ret;
// Copying data here.
readData(2 * pairIndex + 1, ptr, false);
ret.first = *reinterpret_cast<int*>(ptr);
readData(2 * pairIndex + 2, ptr, true);
ret.second = *reinterpret_cast<std::string*>(ptr);
}
void main()
{
std::vector<std::pair<int, std::string>> parsedData;
parsedData.push_back(readPair(0));
parsedData.push_back(readPair(1));
}
Demo
(I removed the references from the readData() signature for brevity - you get the same effect by storing the temporary expressions in variables.)
Generally speaking: Whatever relation between id and the expected data type is should just be turned into the data structure - otherwise you can only reason about the type of your data entries when you know both the current ID and this relation, which is exactly something you should encapsulate in a data structure.
Your readData isn't a useful function. Any attempt at using what it produces gives undefined behavior.
Yes, it's possible to do roughly what you're asking for without a template. To do it meaningfully, you have a couple of choices. The "old school" way would be to store the data in a tagged union:
struct tagged_data {
enum { T_INT, T_STR } tag;
union {
int x;
char *y;
} data;
};
This lets you store either a string or an int, and you set the tag to tell you which one a particular tagged_data item contains. Then (crucially) when you store a string into it, you dynamically allocate the data it points at, so it will remain valid until you explicitly free the data.
Unfortunately, (at least if memory serves) C++11 doesn't support storing non-POD types in a union, so if you went this route, you'd have to use a char * as above, not an actual std::string.
One way to remove (most of) those limitations is to use an inheritance-based model:
class Data {
public:
virtual ~Data() { }
};
class StringData : public Data {
std::string content;
public:
StringData(std::string const &init) : content(init) {}
};
class IntData : public Data {
int content;
public:
IntData(std::string const &init) : content(init) {}
};
This is somewhat incomplete, but I think probably enough to give the general idea--you'd have an array (or vector) of pointers to the base class. To insert data, you'd create a StringData or IntData object (allocating it dynamically) and then store its address into the collection of Data *. When you need to get one back, you use dynamic_cast (among other things) to figure out which one it started as, and get back to that type safely. All somewhat ugly, but it does work.
Even with C++11, you can use a template-based solution. For example, Boost::variant, can do this job quite nicely. This will provide an overloaded constructor and value semantics, so you could do something like:
boost::variant<int, std::string> some_object("input string");
In other words, it's pretty what you'd get if you spent the time and effort necessary to finish the inheritance-based code outlined above--except that it's dramatically cleaner, since it gets rid of the requirement to store a pointer to the base class, use dynamic_cast to retrieve an object of the correct type, and so on. In short, it's the right solution to the problem (until/unless you can upgrade to a newer compiler, and use std::variant instead).
Apart from the problem in given code described in comments/replies.
I am trying to answer your question
vec.push_back(id, &myData<?>); //how can I set the template param to be the type myData point to?
Before that you need to modify vec definition as following
vector<dataStruct<void>> vec;
Now you can simple push element in vector
vec.push_back({id, &mydata, bb});
i have tried to modify your code so that it can work
#include<iostream>
#include<vector>
using namespace std;
template<typename T>
struct dataStruct
{
int id;
T** data;
bool mybool;
};
void readData(int &ID, void*& data, bool& mybool)
{
if (mybool)
{
data = new string("bla");
}
else
{
int b = 0;
data = &b;
}
}
int main ()
{
void* mydata = nullptr;
vector<dataStruct<void>> vec;
bool bb = false;
for (int id = 0; id < 5; id++)
{
if (id%2) bb = true;
readData(id, mydata, bb);
vec.push_back({id, &mydata, bb});
}
}

Valgrind complains of invalid read when accessing struct member through pointer to struct

The struct is defined as such:
struct section_{
int start;
...
};
For reasons I will not go into, I need to pass a pointer to the struct to a function that accepts a void*. The function looks like this:
void* my_fun(void* sec){
section_* section = (section_*)sec;
int start = section->start; // <---- valgrind complains here
...
}
I have a std::vector<section_*> and I need to call my_fun on each of the elements of this vector. I do this like so:
std::vector<section_*> sections = get_sections();
for (int i = 0; i < sections.size(); ++i){
my_fun((void*)sections[i]);
}
The get_sections() function looks something like:
std::vector<section_*> get_sections(){
std::vector<section_*> sections;
section_ sec1;
sec1.start = 0;
...
sections.push_back(&sec1);
return sections;
}
I've tracked the problem down to the line in my_fun that says
int start = section->start;
The error says:
==3512== Invalid read of size 4
==3512== at 0x41A970: my_fun(void*)
...
==3512== Address 0xffeffa2a0 is on thread 1's stack
==3512== 14160 bytes below stack pointer
Even though I'm getting an invalid read, I am still able to access the members of the struct inside my_fun and they are the correct values. Why is that?
I realize that this code is in little bits and pieces, but the actual code is much more complex and lengthy than what I'm showing, though I think I'm showing all the relevant parts. I hope the info I gave is enough.
As mentioned in the comments by #BoPersson, you add a local variable to the vector:
std::vector<section_*> get_sections(){
std::vector<section_*> sections;
section_ sec1; // <- Local, temporary variable
sec1.start = 0;
...
sections.push_back(&sec1); // <- Address of local var
return sections;
// When this function ends, sec1 is no longer valid
}
You can either use new to create sec1 (deleteing it later). Or change the vector type to std::vector<section_> sections;.

value of local variable is gone?

I have this implementation:
//header file:
InfoTables* localInforTable;
typedef txdr_int32 InfoTable;
typedef struct
{
int sendID;
InfoTable *data;
} InfoTables;
// in cpp file
void Retrieval::InfoTableCallBack(int sendID,
InfoTables& infoTables)
{
localInforTable = new InfoTables();
localInforTable.sendId=sendID;
localInforTable->data = infoTables.data;
printf("Data %d, %d\n", localInforTable.sendId, localInforTable->data[0]); // correct data
}
void Retrieval::CheckInfoData()
{
printf("Data %d, %d\n", localInforTable.sendId, localInforTable->data[0]); // sendID is OK but data9[0] is just printing the address
}
I want to copy inforTables in the method InforTableCallBack to a local variable that I can use for other methods. However the data is clean up in CheckInfoData()?
There are various errors with the code. First, data does not point to any allocated memory. Second, memcpy will simply not work for a user defined types that are not trivially copyable. You could use MyData's assignment operator instead:
void myMethod1(Mydata &otherdata)
{
*data = otherdata;
}
Adding to juanchopanza's answer:
assuming that the code has a typo (and if it really is memcpy())
memcpy(&data, &otherdata, sizeof(otherdata)); will simply not work correctly because data is a pointer already. and '&' on a pointer is address of the pointer = simply wrong usage of memcpy

Vector push_back error

So this is the situation.
I have a class
Class L_FullQuote
{
private:
vector<int> time;
..
}
and
Class B
{
L_FullQuote *Symbols[100];
void handle message()
}
Inside handle msg
i have this statement
Symbols[i]->time.push_back(2);
the code builds fine..but when i use the generated dll. the application just crashes..sometimes it takes me to a nxt poiner error in vector..but mostly the whole application just crashes.
It works fine without that line.
Please help
Thanks
You're already using vector, so why not take it one step further? Using std::vector will allow you to focus on writing your functionality, rather than worrying about memory management.
This example differs slightly from what you originally posted. Your original question class B has an array of 100 pointers that each must be initialized. In the example below, we create a std::vector of L_FullQuote objects that is initially sized to 100 objects in the constructor.
class L_FullQuote
{
public:
vector<int> time;
};
class B
{
public:
// Initialize Symbols with 100 L_FullQuote objects
B() : Symbols(100)
{
}
std::vector<L_FullQuote> Symbols;
void handle_message()
{
Symbols[i].time.push_back(2);
// other stuff...
}
};
L_FullQuote *Symbols[100];
Here you declare an array of pointer to L_FullQuote, but you never initialize any of the pointers, so when you call:
Symbols[i]->...
You are dereferencing an invalid pointer. Also note that you have declared time as private (though your code wouldn't even compile this way, s B as a friend of A I assume?)
Simply declaring an array of pointers does not initialize each element to point to a valid object. You need to initialize each one, something like:
for(int i = 0; i < 100; ++i) {
Symbols[i] = new L_FullQuote();
}
Only then do you have an array full of valid pointers. Don't forget to deallocate them though!
time is private member of class L_FullQuote, from class B you don't have access to that field