0
int main(){
    ...
    //Here, other parts of the code are correctly written.
    switch(n){
      case 1:{
              printf("Enter the path to image to be inserted: ");
              char img[30];                          
              scanf(" %[^\n]%*c", img);
              add(&first, img);          //Here is the func call
              break;
      }
     ... 
  return 0;
}

void add(movie **first, char *img){
  movie *temp=(movie*)malloc(sizeof(movie));
  strcpy(temp->img,img);              // Debugger pointing the seg fault here
  if(*first==NULL){
    *first=temp;
    temp->next=*first;
    return;
  }

  movie *prev=*first;
  while(prev->next!=*first){
    prev=prev->next;
  }
  prev->next=temp;
  temp->next=*first;
  return;
}

This piece of code is causing segmentation fault. Debugger is pointing to strcpy line and throwing the following error: Program received signal SIGSEGV, Segmentation fault.
__strcpy_sse2_unaligned ()
at ../sysdeps/x86_64/multiarch/strcpy-sse2-unaligned.S:546
546 ../sysdeps/x86_64/multiarch/strcpy-sse2-unaligned.S: No such file or directory.

Also the struct definition:

typedef struct Node{
  char *img;
  struct Node *next;
}movie;

Can anyone explain what is causing this segmentation fault?

  • 1
    In the definition of `movie` do you have an array or a pointer for the member `img`? Hint: for the `strcpy()` to work without further changes in your code, it needs to be an array. – pmg Oct 18 '20 at 08:59
  • Can you create a [mcve] that demonstrates the issue? You can't use `**` for bold in code tags. You could add a comment like `// <- crash here` though. – Retired Ninja Oct 18 '20 at 08:59
  • 1
    What is `movie`??? – goodvibration Oct 18 '20 at 09:02
  • You're str-copying to temp->img which *seems* to be the problem, yet don't provide the code that shows how movie / movie.img are allocated... Is `img` allocated?? – Déjà vu Oct 18 '20 at 09:03
  • You forgot to allocate space for `temp->img`. Remember, the `img` member of `movie` is just a pointer, so it's initially uninitialized. You need to make an additional call to `malloc` to set it. – Tom Karzes Oct 18 '20 at 09:10
  • I have added struct definition for reference...and strcpy is the issue shown by the debugger – Dibyarup Dutta Oct 18 '20 at 09:10
  • @DibyarupDutta You have your answer. Multiple people have pointed out that you need to allocate space for `temp->img`. You should be able to just fix it now. – Tom Karzes Oct 18 '20 at 09:13
  • 1
    Just remember to free all of the memory you allocate with `malloc` when you're done with it. – Tom Karzes Oct 18 '20 at 09:21

0 Answers0