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.
One problem is that your
tinstance is not properly initialized. You can fix that by it by usingnewinstead ofmallocYour struct holds astring, whose constructor needs to be called. Callingnewensures that thetobject gets constructed properly.then “free” the memory by calling
delete:This points to the second problem, which is that your
tinstance 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 thetobject is guaranteed to outlive the thread:In general, Instead of using raw pointers to dynamically allocated objects, you should use a smart pointer.
As an aside, the
typedefsyntax for declaring astructlooks pretty strange in C++. Normally, you would do this: