Segmentation Fault

#include<stdio.h>
#include<string.h>
#include<stdlib.h>
int main(){
char *s;
char *t, *p;
gets(s);
gets(t);
int k;

   printf("%s\n",s);

   k  = strlen(s)+strlen(t);

   p=malloc(k);
     while(*s!='\0')
     *(p++)=*(s++);

       while(*t!='\0')
       *(p++)=*(t++);


 printf("%s",p);

   return 0;
   }

Common mistake! You’re just declaring the char pointers, you are not allocating any memory for them.

The input strings s and t might not get the memory.

You need to allocate memory for s and t. For example,

char * s = malloc(101*sizeof(char)); 

assuming that input string will not go beyond 100 characters.

After this line, s is a pointer to a location that contains 100 characters. So now, if you use gets(s) then the user-input string will be stored in that location, and you can access them according to your wish.

Similarly, for t.

There are several problems:

  1. one causing segfault is that you are reading s and t and you have no memory for those
  2. another problem I see in k = strlen(s)+strlen(t); or p=malloc(k); you want additional space for ‘\0’, but good practice is to allocate little more memory to prevent such errors p=malloc(k + 10);
  3. your p setting is (in my opinion) weird

Detailed description for 3.), let say that s = ‘1234’ and t = ‘abcd’, you have

 |
 v
' ', ' ', ' ', ' ', ' ', ' ', ' ', ' '

you are setting memory correctly, but also moving your pointer

      |
      v
'1', ' ', ' ', ' ', ' ', ' ', ' ', ' '

           |
           v
'1', '2', ' ', ' ', ' ', ' ', ' ', ' '

so, when you will try to print p at the end, it prints empty string (if you are lucky).

1 Like
//