【问题标题】:Compiler crashing due to linked list error (?)由于链表错误(?)导致编译器崩溃
【发布时间】:2014-05-25 21:09:53
【问题描述】:
Sim simulacao(Sim lista, int lin, int col, int dim)
{

    int conta;
    int contador_conta;
    int x, y; //x=linha, y=col
    char tipo;
    int pop1;

    conta = ((lin * col) * dim) / 100; //nr de células a serem preenchidas
    contador_conta = conta;
    pop1 = conta / 2;
    while (contador_conta != 0)
    {
        contador_conta--;
        x = numero_random(1, lin);
        y = numero_random(1, col);
        if (pop1 != 0)
        {
            tipo = 'O';
            printf("%d\n", x);
            lista = adiciona(lista, x, y, tipo);
            printf("%d\n", x);
            pop1--;
        }
        else
        {
            tipo = 'X';
            lista = adiciona(lista, x, y, tipo);
        }

    }

    return lista;
}

Sim adiciona(Sim lista, int x, int y, char tipo)
{

    Sim novo, aux;

    novo = (Sim)malloc(sizeof(lista));
    if (novo == NULL) //verifica se alocou o espaço com sucesso
    {
        printf("Erro na alocacao de memoria!\n");
        return lista;
    }
    printf("%d\n", x);
    novo->linha = x;
    novo->coluna = y;
    printf("%d\n", x);
    novo->tipo = tipo;
    novo->prox = NULL;
    if (lista == NULL)
    {
        lista = novo; //se a lista estiver vazia, insere no topo da lista
    }
    else
    {
        aux = lista; //insere no fim da lista
        while (aux->prox != NULL)
            aux = aux->prox;
        aux->prox = novo;
        printf("%d\n", x);
    }
    printf("%d\n", x);
    return lista;
}

我在编译我的代码时遇到问题,它在运行 adiciona 函数 2 次后崩溃。我已经放置了一些 printf 以检查它何时崩溃,但是我一直在寻找错误但我找不到它:/ 有什么想法吗?

picture of the crash/error

【问题讨论】:

  • 所以你的意思是当你运行你的代码时它会崩溃。我假设编译完成没有错误或警告?
  • 如果你的代码正在运行,那么编译器没有崩溃。
  • 看来问题出在分配内存阶段,反正现在解决了,各位!

标签: c list crash linked-list


【解决方案1】:
novo=(Sim)malloc(sizeof(lista));

您分配的是指针大小而不是指针大小。将其更改为:

novo = malloc(sizeof *lista);

【讨论】:

  • 天哪,我觉得自己很愚蠢 xD 谢谢你,伙计,现在可以了!
猜你喜欢
  • 2012-05-19
  • 2014-05-25
  • 1970-01-01
  • 1970-01-01
  • 2018-09-03
  • 2012-02-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多