c-memmove和strcat的分段错误


#include <stdio.h>
#include <string.h>

char* longestConsec(char* strarr[], int n, int k)
{
char* longest_arr[k];
unsigned int longest_len = 0;
if (n == 0 || k > n || k <= 0)
return "";

for (int i = 0; i < (n - (k - 1)); i++)
{
/*
if(( strlen(strarr[i]) + strlen(strarr[i + 1]) ) > longest_len)
{
longest_len = strlen(strarr[i]) + strlen(strarr[i + 1]);
memmove(longest_arr1, strarr[i], 10);
memmove(longest_arr2, strarr[i + 1], 10);
}
*/
unsigned int cmp_len = 0;

// get the length of every k consecutive string in a list and add them up to cmp_len
for (int j = 0; j < k; j++)
cmp_len += strlen( strarr[i + j] );

// compare if cmp_len is greater than longest_len then add that string into longest_arr overlap the previous one
if (cmp_len > longest_len)
{
for (int m = 0; m < k; m++)
memmove(longest_arr[m], strarr[i + m], strlen(strarr[i + m]) + 1); // the first suspect
longest_len = cmp_len;
}
}
// if there is more than 1 consecutive string then the output is combine of k consecutive string in the list
if (k > 1)
{
for (int l = k - 1; l >= 0; l--)
strcat(longest_arr[l - 1], longest_arr[l]); // the second suspect
}
// return the longest_arr[0] the string that have been combine
return longest_arr[0];
}

int main(void)
{
// test subject
char* a1[] = {"zone", "abigail", "theta", "form", "libe", "zas", "theta", "abigail"};
char* newstring = longestConsec(a1, 8, 2);
printf("%sn", newstring);
return 0;
}

当我尝试运行时,它出现了分段错误。我怀疑它是memcpy和strcpy函数,但不知道如何修复它。假设代码进入一个字符串列表,然后检查该列表中的k个连续字符串,并打印出这些字符串的串联。

问题在这里

char* longest_arr[k];
for (int m = 0; m < k; m++)  
memmove(longest_arr[m], strarr[i + m], strlen(strarr[i + m]) + 1); /* there is no memory allocated for longest_arr[m] */

由于longest_arr是由k个字符组成的数组,因此应该为每个longest_arr[m]分配内存。例如

for (int m = 0; m < k; m++) {
longest_arr[m] = malloc(SIZE); /* Allocate memory here, define the SIZE */
memmove(longest_arr[m], strarr[i + m], strlen(strarr[i + m]) + 1);
}

不要忘记通过调用free()函数来释放动态分配的内存,以避免内存泄漏。

相关内容

  • 没有找到相关文章

最新更新