简体   繁体   English

链表数组中的分段错误

[英]Segmentation fault in array of linked lists

I'm tryin to create an array of linked lists and have run into a problem with just the array. 我正在尝试创建一个链接列表数组,并且只遇到了数组问题。 The code runs fine(or at least printf runs in the function) but when I try to loops through in main to print I get a segmentation fault and the lines don't print in the newLabel function. 代码运行良好(或者至少在函数中运行了printf),但是当我尝试遍历main进行打印时,出现了段错误,并且在newLabel函数中未打印行。

void newLabel(char *n, Label **p, int len) {
  p[len] = malloc(sizeof(Label));
  p[len]->next = NULL;
  p[len]->name = malloc(sizeof(char) * strlen(n)+1);
  strcpy(p[len]->name, n);
  printf("%s", p[len]->name);
  ++labels;
}

int main(int argc, char const *argv[]) {
  Label *p[100];
  for (labels = 0; labels < 5; labels++) {
    newLabel("Hi", p, labels);
  }

  for (int i = 0; i <= labels; i++) {
    printf("%s", p[labels]->name);
  }
  return 0;
}
  for (labels = 0; labels < 5; labels++) {
    newLabel("Hi", p, labels);
  }

In this loop you allocated first 5 elements of *p 在此循环中,您分配了*p前5个元素

  for (int i = 0; i <= labels; i++) {
    printf("%s", p[labels]->name);
  }

I this next loop you are accessing 6th member which has not been allocated 在下一个循环中,您正在访问尚未分配的第六个成员

Check out your code 签出您的代码

    for (int i = 0; i <= labels; i++) { //problem here 
    printf("%s", p[labels]->name);
  }

you are execute a loop start from 0 to labels(5). 您正在执行从0到labels(5)的循环。 it means it run for labels value 0,1,2,3,4,5 ie 6 times while you are allocate memory for only 5 elements in below code 这意味着它将为标签值0、1、2、3、4、5运行,即6次,而您在下面的代码中仅为5个元素分配了内存

for (labels = 0; labels < 5; labels++) {
    newLabel("Hi", p, labels);
  }

solution is remove = from for loop ie for loop syntax is 解决方案是从for循环中删除=从for循环语法

for (int i = 0; i < labels; i++)

By the end of this loop here 在此循环结束时

for (labels = 0; labels < 5; labels++) {
    newLabel("Hi", p, labels);
  }

labels is 5 which is never initialized, yet in below loop you are still trying to print p[5] labels是5,它从未被初始化,但是在下面的循环中,您仍在尝试打印p[5]

  for (int i = 0; i <= labels; i++) {
    printf("%s", p[labels]->name); // this labels can be 5 here
  }

So loop within boundaries 所以在边界内循环

for (int i = 0; i < labels; i++) {
    printf("%s", p[labels]->name);
  }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM