views:

34

answers:

1

Hi,

I have defined a constant array in one of my classes as:

static const float values[] = {-0.5f,  -0.33f, 0.5f,  -0.33f, -0.5f,   0.33f,};

In the dealloc method of my class, do I need to free the memory occupied by this field? How do I do it? Should I use NSArrays instead?

+1  A: 

No, you never need to free a statically allocated array. It is allocated by the system when the process starts and remains in scope until it exits.

For that matter, you don't need it for a non-static array either, since it is contained within the class, and so lives and dies with the class.

The only time you need to worry about lifetimes is when you allocate the array on the heap, which is a bit tricky to do for an array of const values:

const float *make_values() {
    float *v = (float *)malloc(6*sizeof(float));
    v[0] = -0.5f;
    v[1] = -0.33f;
    ...
    return v;
}

const float *values = make_values();

Only then you would have to worry about releasing the memory at some point, and then you might want to consider using an NSArray property with retain semantics.

Marcelo Cantos
That makes sense. Thank you very much. What is it wasn't static? What if I just had a const array? What should I do then?
ar106
@ar106: I've amended my answer to cover this.
Marcelo Cantos
Thank you very much. That was really helpful.
ar106
@ar106 : You free what you allocate is the thumb rule.
Praveen S