gpt4 book ai didi

c - 使用两个指针的 Strcmp 导致段错误

转载 作者:行者123 更新时间:2023-11-30 19:41:47 24 4
gpt4 key购买 nike

我正在尝试比较两个基本上已经变成字符串的指针。我不知道如何解决这个问题,但是当我运行它时,它在 strcmp 处给我一个段错误。

这是我的代码:

int find_next_string(int *position, char str[], char * mem_start, int mem_size)
{
int found = 0;
char *temp2;
int k = 0;
int i=(*position+1);
char *temp ;
int temp3 = 0;

temp = (char *) calloc(mem_size, sizeof(char));
temp2 = (char *) calloc(mem_size, sizeof(char));
temp3=*position;
while(i!=temp3 && found==0 && k==0){
//for(j=0;i<mem_size;i++){
temp2=mem_start;
// j++;
temp=strstr(temp2, str);
if(strcmp(temp2, temp)==0){
found=1;
k=i;
}
//}
if(i==mem_size)
i=0;
else
i++;
}
if(found)
print_line(k, mem_start, mem_size);
// 1. update the location to the first character matching str
// 2. print the 16-byte word containing the string and repeat
// printing words until all characters in str are displayed
// 3. set found to 1
// if not found, do not change location and do not print
free(temp);
free(temp2);
return found;
}

最佳答案

崩溃很可能不是由于 strcmp 调用造成的,而是由于您重新分配 temp2 然后尝试释放新指针。您对 temp 执行相同的操作。

如果这些新指针不是用malloc(或calloc,本质上是malloc加上memset)分配的那么你将会有未定义的行为,这是崩溃的一个非常常见的原因。对于 temp 它可以指向某些内存的中间,并尝试在该指针上调用 free (即使它指向用 分配的 block 的中间>malloc) 也是 UB。

free 函数必须传递一个由malloc返回的指针,或NULL,没有别的。

关于c - 使用两个指针的 Strcmp 导致段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33182360/

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