views:

139

answers:

2

I've declared a struct in my header file like this:

typedef struct {
NSString *department;
NSString *departmentId;
}  Department;

Department currentDepartment;

This struct is in a fairly simple class. I assign the struct values in viewDidLoad. Just before leaving viewDidLoad, I see the struct values are still there. After the user clicks a segment control, I reassign the struct values. Before assigning values, I see the two struct values are 0x0. I do have NSZombieEnabled, which is printing out this when I mouse over the struct while the app is running and one of my breakpoints have been hit:

MyApp[25722:207] *** -[CFString _cfTypeID]: message sent to deallocated instance 0xfc0e90

I'm not creating an instance of the struct or deallocating it. How can it be getting deallocated?

+1  A: 

No, structs can be freed, but not unless you do that yourself somewhere in your code. What's being deallocated in this case is a string, as can be seen from the error message. Check the objects you're using when you set the department and departmentId members.

In fact, you need to be extra careful about memory management in general when you assign objects to struct members. In this case, you may need to send a -retain message to the strings, or change the way you're creating them so that you use alloc/init... or copy rather than stringWith... or other methods.

jlehr
Clarification: Structs (in the type sense) cannot be freed, chunks of memory can. You'll never pass a variable of a struct type to free, only pointers.
Chuck
C structs can by dynamically allocated with malloc(), calloc(), etc. If a struct is allocated this way it can (and should) be freed. You seem to be confusing that with *defining* a variable of type struct. (And yes, of course, the address of anything that's dynamically allocated must be stored in variable of some pointer type.)
jlehr
+1  A: 

I strongly advise against putting objects in structs if at all possible. Structs are just dumb collections of data and cannot manage their members' memory like objects can with accessors. This means client code will have to take on the responsibilty of retaining and releasing the structs members whenever it deals with them and making sure they are released before the strict goes out of scope — it's not really that easy. You'd be better off creating a lightweight object.

Chuck
I disagree, there are some use cases where a struct makes more sense than a lightweight class. The trick is identifying those rare cases :)
rpetrich
@rpetrich: If you're talking about structs with objects, those cases seem to be so rare I think you're more likely to run into a good case for unsafe goto.
Chuck
Structs of objects are used frequently in iPhone OS's internal representation of the keyboard and autocorrection features (one example)
rpetrich
(I don't mean for my comments to be argumentative. For 99% of cases, structs of objects are the wrong approach)
rpetrich