Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/c/67.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C 链表上的分段错误_C - Fatal编程技术网

C 链表上的分段错误

C 链表上的分段错误,c,C,所以,我的impimel.c文件中有这个函数,它打印了l(*LInt)的每个元素,它在 (l -> prox) -> valor = 2 (l -> prox) -> prox = NULL; 我的提升功能定义明确,我的结构是: typedef struct lligada { int valor; struct lligada *prox; } *LInt; void imprimeL(LInt l){ LInt aux;

所以,我的impimel.c文件中有这个函数,它打印了l(*LInt)的每个元素,它在

(l -> prox) -> valor = 2 
(l -> prox) -> prox = NULL;
我的提升功能定义明确,我的结构是:

typedef struct lligada {

    int valor;
    struct lligada *prox;

} *LInt;

void imprimeL(LInt l){

    LInt aux;

    while(l != NULL){

        printf("%d\n", l-> valor);
        aux = l-> prox;
        free(l);
        aux = NULL;
        l = aux;
    }

}

int main(){

    LInt l = malloc(sizeof(struct lligada));
    l -> valor = 1;
    (l -> prox) -> valor = 2;
    (l -> prox) -> prox = NULL;

    imprimeL(l);

    printf("Ola\n");
    return 0;
}

你可能想要这个:

#include <stdlib.h>
#include <stdio.h>

typedef struct lligada {    
  int valor;
  struct lligada *prox;    
} *LInt;

void imprimeL(LInt l) {    
  LInt aux;

  while (l != NULL) {
    printf("%d\n", l->valor);
    aux = l->prox;
    free(l);
    l = aux;
  }    
}

int main() {    
  LInt l = malloc(sizeof(struct lligada));
  l->valor = 1;

  LInt l1 = malloc(sizeof(struct lligada));
  l->prox = l1;

  l1->valor = 2;
  l1->prox = NULL;

  imprimeL(l);

  printf("Ola\n");
  return 0;
}
#包括
#包括
类型定义结构lligada{
英勇;
结构lligada*prox;
}*皮棉;
无效改进(lintl){
皮棉;
while(l!=NULL){
printf(“%d\n”,l->valor);
aux=l->prox;
免费(l);
l=aux;
}    
}
int main(){
LInt l=malloc(sizeof(struct lligada));
l->valor=1;
LInt l1=malloc(sizeof(struct lligada));
l->prox=l1;
l1->valor=2;
l1->prox=NULL;
imprimeL(1);
printf(“Ola\n”);
返回0;
}
imprimeL
函数中还有一个bug


下一步是使用循环动态创建链表。

当您访问一个您无权访问的内存地址时,会发生分段错误。在为l分配内存时,您的lligada数据结构如下:

int valor                -> some garbage value
struct lligada *prox;    -> NULL pointer
因此,当您访问l->prox->prox时,您试图访问导致seg故障的空指针


为了避免这种情况,您可以在访问prox元素之前为其分配内存。

So。。
(l->prox)
所指向的位置(我指的是
main
的第三行)?您希望将内存分配给
l->prox
@EugeneSh。它指向下一个结构lligada@Cid通过将内存分配给l,我将内存分配给了l->prox.Where在您的代码中?@Leonardomia将您的版本与我的版本进行比较。这应该不难理解。@Leonardomia您的版本只显示并释放列表中的第一个元素。