I normally work in Objective-C, but am now trying to integrate some C code which I don’t know as well.
Let’s start with my Buffer object:
@interface Buffer : NSObject {
int* buffer_;
int numFrames_;
int idNumber_;
}
@property (nonatomic) int* buffer;
@property (nonatomic) int numFrames;
@property (nonatomic) int idNumber;
In another class I’m trying to dynamically create c arrays and stick them into the buffer of my buffer objects. It should be noted that I don’t know how many buffer objects I will need in advance.
for (i=0; i<[arrayOfFlags count]; i++) {
NSNumber *flagObject = (NSNumber*)[arrayOfFlags objectAtIndex:i];
int flagInt = [flagObject integerValue];
Buffer *snippetBuffer = [[Buffer alloc] init];
int returnArray[44000];
snippetBuffer.buffer = returnArray;
snippetBuffer.numFrames = 44000;
snippetBuffer.idNumber = i;
int k;
// NSLog(@"creating snippet buffer at flag %d", flagInt);
for (k = 0; k < 44000; k++) {
snippetBuffer.buffer[k] = // insert some values here.
}
}
When I run this code all the buffer objects have the same data as the last one to be produced. I think what is happening is that the returnArray being overwritten at each iteration.
So how do I ensure that new memory is being allocated each time I instantiate a c array in a loop? (If that is indeed my problem).
Hope this question wasn’t too complicated. Please feel free to ask questions.
This is a wrong initialization for your
snippetBuffer.bufferpointer, sincereturnArrayis a local variable and gets destroyed at the end of the scope.Use instead
Remember to call
freeto release the memory after you have done.