C-字符串复制中的分割故障



我在循环时得到内部的分割故障错误。

char **c;
c=(char **)malloc(3*(N-1)*sizeof(char *));
for(int i=0;i<3*(N-1);)
{
    char *temp;
    gets(temp);
    while(*temp!='$')
    {
        j=0;
        while(*temp!=' ')
        {
            *(c[i]+j)=*(temp+j);
            j++;
        }
        i++;
    }
    i++;
}        

对不起,我知道操纵字符串会导致错误。但是我不确定此错误。

您只是为3 * (N - 1)字符串指针分配空间,但没有为角色本身的空间。temp指针也非专业化,但是您仍使用gets()通过它写作。这导致了不确定的行为。

另外,您不应该在c。

中施放 malloc()的返回值

内存未分配给temp变量。

char *temp;
gets(temp);

1) temp应该是复制gets字符串的内存(缓冲区)块。

char *temp = malloc (256 * sizeof(char)); /* 256 as example*/

2)对于线

while(*temp!='$')

while(*temp!=' ')

我们希望为两个循环找到temp指针的一些增量(例如temp++),但没有。这导致问题

如果我可以猜测您的需求,则在您修复了您的代码(我没有对其进行测试)后,这里

char **c;
c=(char **)malloc(3*(N-1)*sizeof(char *));
char copy[256];
char temp[256], *p;
for(int i=0;i<3*(N-1);i++)
{
    p = temp;
    gets(p);
    while(*p!='$')
    {
        j=0;
        while(*p!=' ')
        {
            *(copy+j)=*p;
            j++;
            p++;
        }
        if(*p=='')
            break;
        p++;
    }
    copy[j] = ''
    c[i] = strdup(copy); // allocate memory with size of copy string and then copy the content of copy to allocated memory
}  

最新更新