Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

String copy in C causing segmentation fault

I am trying to copy a string into another char pointer variable using strcpy function.But I always get segmentation fault.Here is my code.

/* strcat example */
#include <stdio.h>
#include <string.h>

int main()
{
  char str[100]="";
  char *pch3;
  strcpy(pch3,"Ravi");
  //strcat(str,pch3); //Segmnetation fault.
  puts(pch3);
  return 0;
}

If I do the same thing in this one I still get segmentation fault.

 else
      {
         misc_rec_cnt++;
         fp1=fopen("breast-cancer-wisconsin-miscellaneous.data","a");
         fprintf(fp1,"%s",line2);
         fclose(fp1);
         fp2=fopen("missingSCNs.data","a");
         pch2=strtok(line2,",");
         fprintf(fp2,"%s\n",pch2);
         fclose(fp2);

         //pch3=(char *)malloc(sizeof(char)*strlen(line3));
         pch3 = strtok(line3,",");
         while(pch3!=NULL)
         {
             if(strcmp(pch3,"?") == 0)
             {
                strcat(str1,"0");
                strcat(str1,",");
             }
             else
             {
                //strcat(str1,pch3);
                strcat(str1,",");
             }
             pch3 = strtok(NULL,",");
         }
         strlen1=strlen(str1);
         memcpy(str2,str1,strlen1-1);
         fp3=fopen("breast-cancer-wisconsin-miscellaneous-cleansed.data","a");
         fprintf(fp3,"%s\n",str2);
         fclose(fp3);
      }
like image 300
Teja Avatar asked Jul 19 '26 09:07

Teja


2 Answers

You need to allocate the space for pch3 before you copy to it. Use malloc to create a char array large enough to accomodate the elements of your source string before you copy it. What you are currently doing is declaring a char pointer and not initialising it. Therefore the memory location that it points to could be anywhere - and that means that you should probably not be attempting to write to it - which is why you are getting the segfault. Using malloc will allow you to allocate a region of memory that you are safe to write to and this will solve your problem (assuming the call to malloc succeeds). You cannot just go writing data to random memory locations without getting segfaults and access violations.

like image 57
mathematician1975 Avatar answered Jul 21 '26 00:07

mathematician1975


pch3 is a char pointer, but it doesn't have any storage associated with it which is the cause of the problem. Call malloc() to allocate some memory that the pch3 pointer can point to and you should be ok.

At this point you have a char pointer that is uninitialized and just pointing somewhere unknown. So try this:

  pch3 = (char *)malloc(sizeof(char) * 100); /* 100 just as an example */

This tutorial might be helpful or this SO question: Allocating char array using malloc

like image 29
Levon Avatar answered Jul 20 '26 22:07

Levon