字符串复制中的分段错误

时间:2012-11-05 08:28:25

标签: c pointers segmentation-fault strcpy

我得到了内部while循环的分段错误错误。

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++;
}        

抱歉不正确的缩进。我知道操作char *字符串会导致错误。但我不确定这个错误。我想把tmp字符串分成三个不同的字符串。

3 个答案:

答案 0 :(得分:3)

您只为3 * (N - 1)字符串指针分配空间,但没有空间容纳字符本身。 temp指针也未初始化,但您仍然使用gets()来编写它。这导致了不确定的行为。

另外,你是shouldn't cast the return value of malloc(),在C。

答案 1 :(得分:2)

未为temp变量分配内存。

char *temp;
gets(temp);

答案 2 :(得分:0)

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=='\0')
            break;
        p++;
    }
    copy[j] = '\0'
    c[i] = strdup(copy); // allocate memory with size of copy string and then copy the content of copy to allocated memory
}  
相关问题