如何解释将NULL作为参数传递给程序的原因?

时间:2019-03-07 20:59:17

标签: c

我正在尝试连接两个字符串。我将NULL传递给S1和/或S2时收到分段错误。我认为它与第19行通过调试有关,但是由于我的经验不足,我无法弄清楚。

char *string_nconcat(char *s1, char *s2, unsigned int n)
{
        char *p1 = s1, *p2 = s2;
        unsigned int L1 = 0, L2 = 0, c = 0;
        char *cstr, *dest;
        if (s1 == NULL)
                s1 = "";
        if (s2 == NULL)
                s2 = "";
        while (*p1 != 0)
                p1++, L1++;
        while (*p2 != 0)
                p2++; L2++;

        if (n >= L2)
                cstr = malloc((L1 + L2 + 1) * sizeof(char));
        else
                cstr = malloc((L1 + n + 1) * sizeof(char));
        p1 = s1, p2 = s2, dest = cstr;
        if (cstr == NULL)
                return (NULL);

        while (*p1 != '\0')
        {
                *dest = *p1;
                dest++;
                p1++;
        }
        while (*p2 != '\0' && c < n)
        {
                *dest = *p2;
                dest++;
                p2++;
                c++;
        }
        *dest = '\0';

        return (cstr);
}

2 个答案:

答案 0 :(得分:2)

当您检测到已传递NULL时,请将s1s2设置为空字符串,但这不会改变p1 / {{1 }}指向的,因此当您稍后尝试使用它们时,它们仍然指向NULL。

答案 1 :(得分:0)

一秒钟后添加*p1 = s1, *p2 = s2;