使用strcpy将字符串复制到动态分配的结构属性时出现分段错误

问题描述

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;
}

这段代码导致分段错误。调试器指向strcpy行并引发以下错误: 程序收到信号SIGSEGV,分段错误
__strcpy_sse2_unaligned()
在../sysdeps/x86_64/multiarch/strcpy-sse2-unaligned.S:546
546 ../sysdeps/x86_64/multiarch/strcpy-sse2-unaligned.S:没有这样的文件或目录。

还有结构定义:

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

任何人都可以解释造成此细分错误的原因吗?

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)