我正在关注 iOS5 上的 rapidxml 教程,不幸的是我的 c 有点生疏了。以下代码适用于较小的字符大小,但会崩溃
EXC_BAD_ACCESS当我拉下更大的尺寸时(我从 RESTful 接口中提取 XML)。
# pragma mark - parser methods
-(void)parseIncomingFeed:(NSData *)xmlData:(NSString*)tag {
NSString *xmlStringOrg = [[NSString alloc] initWithData:xmlData encoding:NSASCIIStringEncoding];
NSLog(@"[xmlStringOrg length] = %-10d [xmlData length] = %d", [xmlStringOrg length],[xmlData length]);
char xmlString[[xmlStringOrg length]];
strcpy(xmlString, [xmlStringOrg UTF8String]); // <--- crashes here
...
结果如下:
[xmlStringOrg length] = 13580 [xmlData length] = 13580
[xmlStringOrg length] = 115476 [xmlData length] = 115476
[xmlStringOrg length] = 154589 [xmlData length] = 154589
[xmlStringOrg length] = 1902 [xmlData length] = 1902
[xmlStringOrg length] = 23402 [xmlData length] = 23402
[xmlStringOrg length] = 93037 [xmlData length] = 93037
[xmlStringOrg length] = 1723 [xmlData length] = 1723
[xmlStringOrg length] = 172329 [xmlData length] = 172329
[xmlStringOrg length] = 3470671 [xmlData length] = 3470671
(boom! with EXE_BAD_ACCESS leading to: 0x3234af6e: push.w {r3, r4})
盲目地,我尝试了以下但没有运气:
NSString *xmlStringOrg = [[NSString alloc] initWithData:xmlData encoding:NSASCIIStringEncoding];
char xmlString[3600000];
strcpy(xmlString, [xmlStringOrg UTF8String]);
和
NSString *xmlStringOrg = [[NSString alloc] initWithData:xmlData encoding:NSASCIIStringEncoding];
char xmlString[[xmlStringOrg length]];
strncpy(xmlString, [xmlStringOrg UTF8String], [xmlStringOrg length]);
有任何想法吗?从我多年前的 c 课程开始,感觉就像我需要将大小大于 X 并单独处理它们,但我不确定从哪里开始。R
编辑 1 - 工作
感谢@RichardJ.RossIII,以下工作:# pragma mark - parser methods
-(void)parseIncomingFeed:(NSData *)xmlData:(NSString*)tag {
NSString *xmlStringOrg = [[NSString alloc] initWithData:xmlData encoding:NSASCIIStringEncoding];
NSLog(@"[xmlStringOrg length] = %-10d [xmlData length] = %d", [xmlStringOrg length],[xmlData length]);
char *xmlString = (char*) malloc([xmlStringOrg length]);
strcpy(xmlString, [xmlStringOrg UTF8String]); // no more tears
...
free(xmlString);
}