简体   繁体   中英

Segmentation fault in string copying

I'm getting the segmentation fault error for the inner while loop.

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

sorry for improper indentation.I know that manipulating char * strings would cause an error.But I am not sure about this error.I was tring to break tmp string into three different strings.

You are only allocating room for 3 * (N - 1) string pointers, but no room for the characters themselves. The temp pointer is also uninitialized, but you're still writing through it using gets() . This leads to undefined behavior.

Also, you shouldn't cast the return value of malloc() , in C.

Memory is not allocated for temp variable.

char *temp;
gets(temp);

1) temp should be a block of memory (buffer) to copy the gets string.

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

2) for the line

while(*temp!='$')

and

while(*temp!=' ')

we expect to find some incrementation for temp pointer (for example temp++ ) for both loops but there is not. and this cause a problem

If I can guess your need, here after a suggestion of your code fixed ( I did not test it)

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
}  

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM