0

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.

Amit Gupta
  • 277
  • 1
  • 2
  • 9
  • You should compile with all warnings and debugging information (e.g. with `gcc -Wall -g` on Linux) and use the debugger (e.g. `gdb` on Linux). Learning to use the debugger (and the compiler) is practically part of the learning process about programming in *C*. You may also want to use a memory leak detector like `valgrind` – Basile Starynkevitch Nov 05 '12 at 08:31
  • You should also **avoid using `gets`, it is a *dangerous deprecated* function** (and removed from latest *C* standard). You could use `getline` or `fgets` – Basile Starynkevitch Nov 05 '12 at 08:37

3 Answers3

3

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.

Community
  • 1
  • 1
unwind
  • 391,730
  • 64
  • 469
  • 606
2

Memory is not allocated for temp variable.

char *temp;
gets(temp);
Jeyaram
  • 9,158
  • 7
  • 41
  • 63
  • yes. otherwise, pointer will be pointing to some garbage location. so when you try to reference it, segment fault occurs. Either dynamically or by static say `char temp[100];` – Jeyaram Nov 05 '12 at 08:46
0

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
}  
MOHAMED
  • 41,599
  • 58
  • 163
  • 268