iphone ansi c : pointer being freed was not allocated - iphone

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.

Related

eBPF - Is map.update() not causing undefined behaviour?

I'm completely new to eBPF, I tried to find an answer to this but can't so I was hoping to get some help.
Take Liz's ebpf.py example
It looks like this:
BPF_HASH(clones);
int hello_world(void *ctx) {
u64 uid;
u64 counter = 0;
u64 *p;
uid = bpf_get_current_uid_gid() & 0xFFFFFFFF;
p = clones.lookup(&uid);
if (p != 0) {
counter = *p;
}
counter++;
clones.update(&uid, &counter);
return 0;
}
This then makes me wonder, for the map named clones she calls the update method. She enters a pointer to a stack-allocated variable (counter), does this not cause undefined behaviour when the stack frame is deallocated.
A possible option is that the value within the pointer is copied instead of stored as a pointer.
But then, according to this reference guide BPF_HASH can specify the leaf_type (value of the map). Meaning you can set it to a struct, which can't necessarily be copied.
I feel like I'm missing something so I'm thankful for any explanation for the matter.
A possible option is that the value within the pointer is copied instead of stored as a pointer.
That's correct. The value pointed to by the pointer is copied in the memory buffer allocated for the map's value.
Meaning you can set it to a struct, which can't necessarily be copied.
Why wouldn't that be possible? Note the kernel doesn't really care that it's a struct. It sees a pointer to a memory buffer with a size (the map's value size); it simply copies whatever is in that buffer to the memory buffer allocated for the map value.

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.

access violation in destroy()

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.

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.

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.