首页 > 解决方案 > 如何使用结构修复函数中的分段错误(核心转储)

问题描述

尝试初始化函数,使其数据成员的数值为 0,字符串为“无”,但 strcpy 出现分段错误。

这是用于创建由 x,y 点组成的二维数组的代码,在后面的功能之前,我需要将函数初始化为默认值(0 和无)。我试图弄乱指针而不是使用 strcpy 但据我了解更新字符串,需要 strcpy 。

typedef struct Hill {
  char name[20];
  int loc[2];
  double height;
  double slope;
} Hill;

Hill* setHill (Hill* hill){
  strcpy(hill->name, "none");  // error appears to be here
  hill->loc[0] = 0;
  hill->loc[1] = 0;
  hill->height = 0;
  hill->slope = 0;
  return hill;
}
int main() {
   Hill* hillsArray[5];
   int i;

// calling setHill to populate an array of 5 hills
   for(i=0; i<5; ++i) {
     setHill(hillsArray[i]);
   }

// updating hill "ada's apex" 
strcpy((hillsArray[0]->name), "Ada's Apex");
hillsArray[0]->loc[0] = 12;
hillsArray[0]->loc[1] = 9;
hillsArray[0]->height = 20;
hillsArray[0]->slope = 0.25;

// updating hill turing's top
strcpy((hillsArray[1]->name), "Turing's top");
hillsArray[1]->loc[0] = 4;
hillsArray[1]->loc[1] = 3;
hillsArray[1]->height = 20;
hillsArray[1]->slope = 0.33;

山的更新重复了 3 次,总共 5 个山,但它的相同代码只是用不同的值更新每个山。

标签: c

解决方案


至少有一个问题,您没有为 Hills 分配任何内存。Hill* hillsArray[5];是一个Hill 指针数组。它们指向任何地方,所以当你这样做时hill->name,你正在取消引用一个错误的指针,这是未定义的行为,在你的情况下它表现为一个段错误。您需要Hill动态或自动为每个对象分配内存,如下所示:

// dynamically (following what you have now)
int main() {
   Hill* hillsArray[5];
   int i;

// calling setHill to populate an array of 5 hills
   for(i=0; i<5; ++i) {
     hillsArray[i] = malloc(sizeof(hillsArray[0]));  // equivalent to malloc(sizeof(struct Hill));
     if (hillsArray[i] == NULL)
     {
       // in the case the malloc fails, handle the error however you want
       printf("Could not allocate memory for Hill %d\n", i);
       return 1;
     }
     setHill(hillsArray[i]);
   }
   ....
   // it's considered good practice to clean up memory you dynamically allocate,
   // although you will find differing opinions of that on SO, so up to you.
   // When your process exits, the OS will clean up any allocated memory, so
   // in this case, it's not all that important to clean it up yourself. But
   // for programs that run indefinitely, it's much more of a concern.
   for (i=0; i<5; i++)
   {
     free(hillsArray[i]);
   }
}

或者,如果您不想弄乱动态分配内存(除非必须这样做,否则我不会),您可以

// setup Hills in automatic storage instead
int main() {
   Hill hillsArray[5]; // each hill is in automatic storage, probably on the stack
   int i;

// calling setHill to populate an array of 5 hills
   for(i=0; i<5; ++i) {
     setHill(&(hillsArray[i]));  // now you must pass the address of each Hill to the setHill function
   }

   ....

   // since it's automatic storage, no need to clean it up yourself
}

推荐阅读