views:

5646

answers:

2

Given a struct, e.g.

typedef struct
{
  int value;
} TestStruct;

Why does the following code (in the context of an Objective-C class running on the IPhone) throw a "non-aligned pointer being freed" exception?

TestStruct ts = {33};
free(&ts);

N.B. My uber goal is to use a C library with many vector-math functions, hence the need to find out some viable way to mix C and Objective-C

+5  A: 

Because you are trying to free something that was allocated on the stack. The function free() can only be called on memory that was allocated with malloc().

JSBangs
True. But this person doesn't seem to have a good grasp of heap v. stack, so let's not confuse him with the subtleties of various kinds of static allocation :).
JSBangs
Exactly! (from the Java person in question :-)
Ariel Malka
Java is no excuse... :)
Rui Pacheco
+10  A: 

It looks to me like you're trying to free a stack or static variable. You need to have malloc()'d something for it to be able to be free()'d.

Try this instead:

TestStruct *ts = malloc(sizeof(TestStruct));
ts->value = 33;
free(ts);

For those more familiar with object-oriented languages, you might find it helpful to create a constructor:

TestStruct *newTestStruct(int value)
{
    TestStruct *ret = malloc(sizeof(TestStruct));
    ret->value = value;
    return ret;
}

This enables you to allocate a struct and set the values in one step. Just remember that this value should be freed once it's no longer useful:

TestStruct *x = newTestStruct(3);
free(x);
Kyle Cronin
Makes perfect sense, thanks! But then: any mean to allocate and populate at the same time?
Ariel Malka
No direct way, but you can create your own constructor if you want. I edited the post to explain how to do that.
Kyle Cronin
Thank you to the people that voted this answer up after the edit. I just got into the 10k club! :-D
Kyle Cronin
I does not understand what happen if when we got a lot of votes from reader of the question with answer? I want to say meaning 10K club?
RRB