gpt4 book ai didi

c++ - iPhone 应用程序因 C++ 代码而崩溃

转载 作者:塔克拉玛干 更新时间:2023-11-03 06:54:02 24 4
gpt4 key购买 nike

我编写了一段代码来为我的应用程序实现 LCS 算法。在这个算法中,我使用 malloc 实现了一个数组。但是,我不确定我是否做错了什么。我找不到显示原因的任何具体消息。我找不到出路。

注意:我有电弧

我的代码如下

- (IBAction)buttonAction:(id)sender
{
[self getInlineDiffofFragment1:[NSArray arrayWithObjects:@"line1", @"line2", @"line3", @"line4", @"line5", nil] andFragment2:[NSArray arrayWithObjects:@"line1", @"line2", @"line4", @"line6", nil]];
}

- (void)getInlineDiffofFragment1:(NSArray*)fragment1 andFragment2:(NSArray*)fragment2
{
int row = fragment1.count + 1;
int col = fragment2.count + 1;
int *lcs = (int*)malloc(sizeof(int) * row * col); //2d array
NSString *str;
for (int i = 0; i <= fragment1.count; i++) {
lcs[i * row] = 0;
}
for (int j = 0; j <= fragment2.count; j++) {
lcs[0 + j] = 0;
}

for (int i = 1; i < row; i++) {
str = [NSString stringWithFormat:@""];
for (int j = 1; j < col; j++) {
int xy = i * row + j;
if ([[fragment1 objectAtIndex:i - 1] isEqualToString:[fragment2 objectAtIndex:j - 1]]) {
lcs[xy] = lcs[(i - 1) * row + (j - 1)] + 1;
} else {
lcs[xy] = MAX(lcs[(i - 1) * row + j], lcs[i * row + (j - 1)]);
}
str = [str stringByAppendingFormat:@"%d ", lcs[xy]];
}
NSLog(@"%@", str);
}

free(lcs);
NSLog(@"freed");
}

该函数按预期完美打印结果并退出该 block 。结果如下

2012-09-26 16:14:18.727 TestDiff[56178:11303] 1 1 1 1 
2012-09-26 16:14:18.733 TestDiff[56178:11303] 1 2 2 2
2012-09-26 16:14:18.734 TestDiff[56178:11303] 1 2 2 2
2012-09-26 16:14:18.735 TestDiff[56178:11303] 1 2 3 3
2012-09-26 16:14:18.736 TestDiff[56178:11303] 1 2 3 3
2012-09-26 16:14:18.736 TestDiff[56178:11303] freed

打印结果并退出 block 后它崩溃了。崩溃报告如下

enter image description here

程序对下面的测试功能没问题

#define WIDTH 4
#define HEIGHT 5
#define INDEXOF(x,y) ((y*WIDTH) + x)

- (void)testArray
{
NSString *str;
int *myArray = (int *) malloc(sizeof(int) * 5 * 4); // 4 * 5 array
for(int x=0; x<WIDTH; x++){
str = [NSString stringWithFormat:@""];
for(int y=0; y<HEIGHT; y++){
myArray[INDEXOF(x,y)] = y;
str = [str stringByAppendingFormat:@"%d ", myArray[INDEXOF(x, y)]];
}
NSLog(@"%@", str);
}
free(myArray);
}

谢谢你的帮助

最佳答案

您是否尝试过在 free(myArray); 行上放置一个断点?它是否成功地到达了那个点,然后当你跨过它时崩溃了?

此外,如果您收到 EXC_BAD_ACCESS,您应该尝试 turning zombies on看看是否已经发布了一些东西。

关于c++ - iPhone 应用程序因 C++ 代码而崩溃,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12611426/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com