开发者

Is this acceptable practice initialize array on the heap?

Is this acceptable code?:

unsigned char *buffer= malloc(16 * sizeof(*buffer));
        if (buffer == NULL) {
            errorText.text= @"Insufficient memory.";
            NSLog(@"%@",@"Insufficient memory.");
            return;
        }
        unsigned char temp[16]= {1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16};
        memcpy(buffer,temp,16);
        NSData* seed= [NSData dataWithBytesNoCopy:buffer length:16];

or:

unsigned char *buffer= malloc(16 * sizeof(*buffer));
if (buffer == NULL) {
    errorText.text= @"Insufficient memory.";
    NSLog(@"%@",@"Insufficient memory.");
    return;
}
memset(buffer,0,16); // set all bytes to zero
buffer[0]= 0x01;
buffer[1]= 0x02;
buffer[2]= 0x03;
buffer[3]= 0x04;
buffer[4]= 0x05;
buffer[5]= 0x06;
buffer[6]= 0x07;
buffer[7]= 0x08;
buffer[8]= 0x09;
buffer[9]= 0x0a;
buffer[10]= 0x0b;
buffer[11]= 0x0c;
buffer[12]= 0x0d;
buffer[13]= 0x0e;
buffer[14]= 0x0f;
buffer[15]= 0x开发者_JS百科10;
NSData* seed= [NSData dataWithBytesNoCopy:buffer length:16];

My C is a bit rusty!


[ edited to remove bogus advice about not using malloc with dataWithBytesNoCopy]

Another option would be to just use -dataWithBytes: and let NSData take care of the copying for you:

    static unsigned char seedBytes[16]= {1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16};
    NSData* seed= [NSData dataWithBytes:seedBytes length:16];
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜