C-array return and memory management

I am a little puzzled by the following pointsclass property MKMultiPointin MapKit:

@property (nonatomic, readonly) MKMapPoint *points

It returns a struct array. You can find out the number of elements in an array with a property pointCount.

With my limited knowledge of C, I always thought that C-arrays can only be "sort of returned" if they are passed by reference to a function, because the caller is responsible for allocating memory and then freeing it.

If I wrote a similar property that would allocate memory for an array (supposedly called) and, more importantly, who would free it (supposedly called)? That sounds a little risky to me. In addition, the documentation for the above property says nothing about the need to free memory.

What am I missing?

+3
source share
2 answers

(An example code is in C).

It is good practice to allocate and release a resource at the same level. There are two ways to define a function that returns an array of things:

// `points` are allocated and freed by the caller.
void MakePoints (MKMapPoint *points, size_t number_of_points);

// usage:
size_t count = 10;
MKMapPoint *points = malloc (sizeof (MKMapPoint) * 10);
MakePoints (points, count);

// Use points

free (points);

// or simply
MKMapPoint points[10];
MakePoints (points, 10);

// Use points

The second way is to let the library function manage memory:

MKMapPoint *MakePoints (size_t number_of_points);
void FreePoints (MKMapPoint *points);

// Usage:
MKMapPoint *points = MakePoints (10);

// Use points

// The library need not necessarily call free() on points,
// it might reuse it in further calls to MakePoints().
FreePoints (points);
+3
source

The receiver, in most cases, will handle memory allocation. Who releases him depends on how you determine the right of ownership. Is the memory allocated by the recipient no longer needed after it is returned? If so, you should probably mention in your documentation that the caller needs to free the returned array. If the receiver can reuse the returned memory, leave it free.

, , , :

- (NSUInteger) mapPointCount;
- (void) getMapPoints:(MKMapPoint *)pointsOut;

obj.mapPointCount MKMapPoints . / .

, // , , . , , const MKMapPoint * - (, , , , ).

, NSData - , . , , , . , , , , .

0

All Articles