access violation in destroy() - destructor

I am trying to manage the lifetime from an expensive object using manual memory management and during my unit-tests I seem to crash my program with an access violation in the main method underneath destroy(bar) in this example.
This is the minimal example for my problem where I get an access violation.
I don't understand what's going wrong.
class Foo { int i;}
struct Bar
{
Foo _p;
this(Foo foo)
{
_p = foo;
}
~this() {
import core.stdc.stdlib : free;
if (_p !is null)
{
destroy(_p);
free(cast(void*)_p);
_p = null;
}
}
}
void main(string[] argv)
{
import std.conv;
import core.stdc.stdlib;
Foo foo = emplace(cast(Foo) malloc(Foo.sizeof));
Bar bar = Bar(foo);
destroy(bar);
}

Note that destroy sets _p to null "for" you... which means you never actually free it. Do Foo tmp = _p; destroy(_p); free(cast(void*) tmp); instead, or something like that, so you keep a temporary copy of the reference beyond the destroy call. That's not what's causing your crash though, that is just a memory leak.
The crash is because, Foo.sizeof for a class is the size of the reference, not the size of the instance. For classes, you want to malloc(__traits(classInstanceSize, Foo)). The documentation mentions this as one of its preconditions: http://dpldocs.info/experimental-docs/std.conv.emplace.3.html
That's causing your crash because you didn't allocate enough space for the vtable (and thus emplace probably corrupted memory too, which eluded type checks due to your cast!). I would malloc and slice it instead of casting it.
// malloc the instance size then slice it to get a type-safe representation
void[] memory = malloc(__traits(classInstanceSize, Foo))[0 .. __traits(classInstanceSize, Foo)];
emplace!Foo(memory); // emplace a new one in that memory
You also should be careful when passing class references to that struct, since if it wasn't malloced or if there is another reference, you will get a dangling problem.

Related

Using of __block variable inside a block

I have a class like this
class MyClass{
public:
MyClass(const int *a, int *aC= nullptr);
MyClass(MyClass &myClass) = delete;
MyClass(MyClass &&yClass) noexcept;
}
I have my processor function defined like this
my_processor = ^(int* c1, const int* a1){
__block MyClass obj(a1 c1);
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^(void)
{
ProcessMyData(obj);
});
}
When i run the code, i get a crash like this
0 libsystem_platform.dylib 0x00007fff20359029 _platform_memmove$VARIANT$Haswell + 41
1 libsystem_blocks.dylib 0x00007fff2004f3d1 _Block_copy + 117
What am i doing wrong?
I don't think we'll be able to conclusively find the source of your problem given the code you've provided, as it's insufficient to reproduce the issue.
The most obvious possibility that stands out to me is:
my_processor = ^(int* c1, const int* a1){
__block MyClass obj(a1 c1);
dispatch_async(
Here, c1 and a1 are pointers. I assume that unlike in the code you posted, these parameters to the constructor influence the constructed object's state in some way. Does their lifetime matter for the internal state of the object? In other words, is either of the pointers stored in the object, and will it be dereferenced later? The block passed to dispatch_async() is likely called on a different thread, at an indeterminate point in time.
So if either of the pointers is stored in MyClass, they must remain valid until the async dispatch is guaranteed to have completed. (Consider copying the data instead of storing the pointer if this is hard to guarantee.)
It would probably also help to know the exact timing of the crash. You could also explicitly _Block_copy for diagnostic purposes instead of letting it happen on demand to see if that provokes a crash too.
But essentially, you haven't provided enough context here to give anything close to a definitive answer. Edit your question so that the code is runnable and exhibits the crash and we can help you.

iphone ansi c : pointer being freed was not allocated

I am using a c lib in my iPhone application. The c lib is written by someone I do not have access to.
However I am getting the error that object 0xa6000d is being freed but not allocated. The debug variable screenshot is here.
struct GtsMsg is defined as,
struct msg {
int offset;
int dataLength;
u8* data;
cBool expandable;
cBool owned;
u8* mid2key;
};
#define GtsMsg struct msg
void freeMessageData(GtsMsg* msg) {
if (msg == NULL) return;
if (msg->owned) {
if (msg->data != NULL) {
free(msg->data);
}
}
free(msg->mid2key);
memset(msg, 0, sizeof(GtsMsg));
}
The breakpoint for malloc_error_break is the line free(msg->data).
I have added the checking if (msg->data != NULL), but it did not work. What are the ways to check if the memory for msg->data or for msg is allocated or not?
Do you think there is something fishy, at *data = (u8)'\0'?
thanks in advance!
Thanks to all to your suggestions.
Thanks hmjd for your tips.
I found the struct is used in a cpp class which destructor calls the freeMessageData. But I could not find that the struct is initialized. So, if I initialize the struct to NULL in the declaration, this avoid the free memory problem and do not crash.
Its something suggested by simonc. If he writes that as an answer not, comment, I could accept that.
From comments of hmjd,
The check for NULL is useless as free() will be a no-op if the pointer
passed to it is NULL. Just because a pointer is not NULL does not mean
it points a valid memory location (the memory may have already been
freed or the pointer was never initialized to NULL). It is the
responsibility of the programmer to ensure that the pointer is valid
before attempting to free it.

Pointer to a derived class object

following problem:
I want to build a function which returns me a Pointer to an derived object from an abstract class. I think, the memory is freed when the function is left because i get an alloc-error. But i can't give the object back, because the class is abstract. In the function i decide, which derived class the object will be have. How can I solve the problem?
Any idea?
QgsSymbolV2* QGISFunc::ReadClassSymbolsXML(QString FeatureType, QXmlStreamReader &reader)
{
QgsMarkerSymbolV2* p_mlmSymbol=0;
try
{
QgsLineSymbolV2 mllSymbol;
QgsFillSymbolV2 mlfSymbol;
QgsMarkerSymbolV2 mlmSymbol;
...
return &mlmSymbol; // alloc error
You are returning the address of a variable with automatic storage. That object gets destroyed when the function returns. The solution is to allocate the object on the heap. I suggest using a smart pointer (unique_ptr or shared_ptr in combination with make_shared<>()) for that purpose and return the smart pointer.
std::shared_ptr<QgsSymbolV2> QGISFunc::ReadClassSymbolsXML(
QString FeatureType,
QXmlStreamReader &reader
)
{
try
{
...
std::shared_ptr<QgsSymbolV2> spObj = make_shared<QgsMarkerSymbolV2>();
...
return spObj;
}
...
}
Your problem has nothing to do with the class being abstract. You create an object on the stack and then return its address. That address though will no longer be valid after the function returns. If you really want to return a pointer and delegate ownership to the caller, why not create it on the heap with new? Don't forget to delete it though later when you are done with that object, or consider smart pointers as #AndyProwl suggests.

struct vs class for writing D wrappers around foreign languages

(note: this is related to Usage preference between a struct and a class in D language but for a more specific use case)
When writing a D interface to, say, C++ code, SWIG and others do something like this:
class A{
private _A*ptr;//defined as extern(C) elsewhere
this(){ptr=_A_new();}//ditto
this(string s){ptr=_A_new(s);} //ditto
~this(){_A_delete(ptr);} //ditto
void fun(){_A_fun(ptr);}
}
Let's assume no inheritance is needed.
My question is: wouldn't it be preferable to use a struct instead of a class for this?
The pros being:
1) efficiency (stack allocation)
2) ease-of-use (no need to write new everywhere, eg: auto a=A(B(1),C(2)) vs auto a=new A(new B(1),new C(2)) )?
The cons being:
require additional field is_own to handle aliasing via postblit.
What would be the best way to do so?
Is there anything else to worry about?
Here's an attempt:
struct A{
private _A*ptr;
bool is_own;//required for postblit
static A opCall(){//cannot write this() for struct
A a;
a.ptr=_A_new();
a.is_own=true;
return a;
}
this(string s){ptr=_A_new(s); is_own=true;}
~this(){if(is_own) _A_delete(ptr);}
void fun(){_A_fun(ptr);}
this(this){//postblit;
//shallow copy: I don't want to call the C++ copy constructor (expensive or unknown semantics)
is_own=false; //to avoid _A_delete(ptr)
}
}
Note the postblit is necessary for cases when calling functions such as:
myfun(A a){}
I suggest that you read this page. The only functions on C++ classes that you can call in D are virtual functions. That means that
D can­not call C++ spe­cial mem­ber func­tions, and vice versa. These in­clude con­struc­tors, de­struc­tors, con­ver­sion op­er­a­tors, op­er­a­tor over­load­ing, and al­lo­ca­tors.
And when you declare a C++ class in D, you use an extern(C++) interface. So, your class/struct would look like this
extern(C++) interface A
{
void fun();
}
However, you'd need another extern(C++) function to allocate any objects of type A, since it's C++ code that has to do that as the D code doesn't have access to any of the constructors. You'd also need a way to pass it back to C++ code to be deleted when you're done with it.
Now, if you want to wrap that interface in a type which is going to call the extern(C++) function to construct it and the extern(C++) function to delete it (so that you don't have to worry about doing that manually), then whether you use a class or struct depends entirely on what you're trying to do with it.
A class would be a reference type, which mirrors what the C++ class actually is. So, passing it around would work without you having to do anything special. But if you wanted a guarantee that the wrapped C++ object was freed, you'd have to do so manually, because there's no guarantee that the D class' finalizer would ever be run (and presumably, that's where you'd put the code for calling the C++ function to delete the C++ object). You'd have to either use clear (which will actually be renamed to destroy in the next release of the compiler - dmd 2.060) to destroy the D object (i.e. call its finalizer and handle the destruction of any of its member variables which are value types), or you'd have to call a function on the D object which called the C++ function to delete the C++ object. e.g.
extern(C++) interface A
{
void fun();
}
extern(C++) A createA();
extern(C++) void deleteA(A a);
class Wrapper
{
public:
this()
{
_a = createA();
}
~this()
{
deleteA(_a);
}
auto opDispatch(string name, Args...)(Args args)
{
return mixin("_a." ~ name ~ "(args)");
}
private:
A _a;
}
void main()
{
auto wrapped = new Wrapper();
//do stuff...
//current
clear(wrapped);
//starting with dmd 2.060
//destroy(wrapped);
}
But that does have the downside that if you don't call clear/destroy, and the garbage collector never collects your wrapper object, deleteA will never be called on the C++ object. That may or may not matter. It depends on whether the C++ object really needs its destructor to be called before the program terminates or whether it can just let its memory return to the OS (without its destructor being called) when the program terminates if the GC never needs to collect the wrapper object.
If you want deterministic destruction, then you need a struct. That means that you'll need to worry about making the struct into a reference type. Otherwise, if it gets copied, when one of them is destroyed, the C++ object will be deleted, and the other struct will point to garbage (which it will then try and delete when it gets destroyed). To solve that, you could use std.typecons.RefCounted. Then you get something like
extern(C++) interface A
{
void fun();
}
extern(C++) A createA();
extern(C++) void deleteA(A a);
struct Wrapper
{
public:
static Wrapper opCall()
{
Wrapper retval;
retval._a = createA();
return retval;
}
~this()
{
if(_a !is null)
{
deleteA(_a);
_a = null;
}
}
auto opDispatch(string name, Args...)(Args args)
{
return mixin("_a." ~ name ~ "(args)");
}
private:
A _a;
}
void main()
{
auto wrapped = RefCounted!Wrapper();
//do stuff...
}
You could also define the wrapper so that it has the ref-counting logic in it and avoid RefCounted, but that would definitely be more complicated.
Regardless, I would definitely advise against your suggestion of using a bool to mark whether the wrapper owns the C++ object or not, because if the original wrapper object gets destroyed before all of the copies do, then your copies will point to garbage.
Another option if you did want the C++ object's copy constructor to be used (and therefore treat the C++ object as a value type) would be to add an extern(C++) function which took the C++ object and returned a copy of it and then use it in a postblit.
extern(C++) A copyA(A a);
this(this)
{
if(_a !is null)
_a = copyA(a);
}
Hopefully that makes things clear enough.

Understanding the Objective-C++ __block modifier

I need to do some maintenance on an Objective-C application (updating it to use a new API), and having never used the language before, I'm a bit confused.
I have an Objective-C++ class which implements an interface from my API, and this is used within a block, however whenever it is accessed within the block, it fails with an access violation error (EXC_BAD_ACCESS).
Furthrer investigation shows that none of the constructors for the object in question are being called. It is declared within the containing scope, and uses the __block modifier.
To try and understand this, I made a quick scratch application, and found the same thing happens there:
class Foo
{
public:
Foo() : value(1) { printf("constructor"); }
void addOne() { ++value; printf("value is %d", value); }
private:
int value;
};
void Bar()
{
Foo foo1; // prints "constructor"
__block Foo foo2; // doesn't print anything
foo1.addOne(); //prints "2"
foo2.addOne(); //prints "1"
}
Can anyone explain what is happening here? Why isn't my default constructor being called, and how can I access the object if it hasn't been properly constructed?
As I understand it, your example there isn't using a block as such, but is declaring foo2 as to be used by a block.
This does funny things to the handling of foo2, which you can read more about here.
Hope that helps.
Stumbled upon this old question. This was a bug that's long been fixed. Now __block C++ objects are properly constructed. If referenced in a block and the block is copied, the heap copy is move-constructed from the original, or copy-constructed if it cannot be move-constructed.