Attempt to read or write protected memory when value to pointer
c++, compiler-errors
Solution
One problem is that your `t` instance is not properly initialized. You can fix that by it by using `new` instead of `malloc` Your struct holds a `string`, whose constructor needs to be called. Calling `new` ensures that the `t` object gets constructed properly.
t* arglist = new t;
then "free" the memory by calling `delete`:
delete arglist;
This points to the second problem, which is that your `t` instance must be guaranteed to be alive during the whole execution of the thread. You should not de-allocate its memory until the thread is finished. This is a C++ example where the `t` object is guaranteed to outlive the thread:
#include <thread>
int main()
{
t arglist = whatever;
std::thread t(startover, &whatever); // launches thread which runs startover(&arglist)
// do other stuff
t.join(); // wait for thread execution to finish
}
In general, Instead of using raw pointers to dynamically allocated objects, you should use a smart pointer.
As an aside, the `typedef` syntax for declaring a `struct` looks pretty strange in C++. Normally, you would do this:
struct t {
string fName;
string str;
};
Problem
I have this code: ``` typedef struct { string fName; string str; }t; //-------Other functions------// void BeginTh() { string arg = "yes"; t *arglist; arglist = (t*)malloc(sizeof(t)); arglist->fName = "comBomber"; arglist->str = arg; _beginthread(startOver, 0, (void*)arglist); free(arglist); } ``` And at 'arglist->fName = "comBomber";' i get this error: ``` An unhandled exception of type 'System.AccessViolationException' occurred in <appname> Additional information: Attempted to read or write protected memory. This is often an indication that other memory is corrupt. ``` Anyone can help me ? How solve this problem ? Thanks.