Member Avatar for b1izzard

I got the Segmentation fault error with the following code to
concatenate two strings without using string library functions.

void string_concat()
  {
    int len1,len2,i,j;
   char inpt_str1[30],inpt_str2[30],concat_str[60];
   /*Input string1 and calculate its length */
   printf("\nEnter the String 1 : \n");
   scanf("%s",inpt_str1);

   for(i=0;inpt_str1[i]!='\n';i++)
    {
      len1+=1;
      concat_str[i]=inpt_str1[i];
    }
   
   /*Input string2 and calculate its length */
   printf("\nEnter the String 2 : \n");
   scanf("%s",inpt_str2);
   
   for(i=0;inpt_str2[i]!='\n';i++)
    {
     len2+=1;
    }
  
   for(i=len1,j=0;i<=(len1+len2);i++,j++)
     {
       concat_str[(i+1)]=inpt_str2[j];
     }
   printf("\nThe Concatenation of Two strings is : %s",concat_str);
 }
[TEX]Program received signal SIGSEGV, Segmentation fault.
0x0804877b in string_concat () at str.c:95
95	       concat_str[(i+1)]=inpt_str2[j];[/TEX]

I don't know how to rectify the mistake?.

Well, the error tells you what line the error manifests on, so your first step would be to run your program in a debugger (or use debug printfs if you want to go old school) and verify the state of the variables. Most likely one of your indices is incorrect and steps out of bounds.

Here's one big error:

scanf("%s",inpt_str1);

   for(i=0;inpt_str1[i]!='\n';i++)
    {
      len1+=1;
      concat_str[i]=inpt_str1[i];
    }

scanf() does NOT include the newline char, into the string - that's fgets(). scanf() (infamously!) leaves the newline behind.

So there is no stopping your loop. Change the '\n' to '\0' (the end of string marker) (which scanf() DOES include, for strings.

You do this same error in two places, at least.

Member Avatar for b1izzard

Thanks for the replies. shit! I often forgot the simple basics!

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.