How to free a C-structure?

For structure, for example

typedef struct { int value; } TestStruct; 

Why does the following code (in the context of the Objective-C class running on the iPhone) throw an exception "not aligned pointer exception"?

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

NB My goal of uber is to use the C library with many vector mathematical functions, so you need to figure out some viable way to mix C and Objective-C

+4
source share
2 answers

It seems to me that you are trying to free a stack or a static variable. You need to have malloc () 'd so that it can be free ()' d.

Try this instead:

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

For those who are more familiar with object-oriented languages, it might be useful to create a constructor:

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

This allows you to highlight the structure and set values โ€‹โ€‹in one step. Just remember that this value should be freed when it is no longer useful:

 TestStruct *x = newTestStruct(3); free(x); 
+25
source

Because you are trying to free what was allocated on the stack. The free () function can only be called into memory that was assigned using malloc ().

+7
source

All Articles