memmove和strcat的分段错误

时间:2018-11-26 15:17:06

标签: c segmentation-fault

#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("%s\n", newstring);
    return 0;
}

当我尝试运行它时,出现细分错误。我怀疑这是memcpy和strcpy函数,但不知道如何解决。 该代码假定先获取一个字符串列表,然后检查该列表中的k个连续字符串,然后打印出这些字符串的串联。

1 个答案:

答案 0 :(得分:0)

问题在这里

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()函数来释放动态分配的内存,以避免内存泄漏。