【问题标题】:Tabu Search Algorithm always crashing on the second iteration [closed]禁忌搜索算法总是在第二次迭代时崩溃[关闭]
【发布时间】:2017-09-11 13:35:49
【问题描述】:
typedef struct{
    int *sols;
    int rest;
    int fitness;
    int num;
    struct lista* next;
}lista;

lista* gere_lista(lista *solucoes, int *sol, int *grafo, int objs, int rests){
    int i;
    int *nova_sol;
    lista *temp = solucoes;
    nova_sol = malloc(sizeof(int)*objs);
    nova_sol = update_sol(sol, nova_sol, objs);
    for(i=0; i<objs; i++){
        nova_sol = gera_vizinho3(nova_sol, i);
        temp->sols = malloc(sizeof(int)*objs);
        temp->sols = update_sol(nova_sol, temp->sols, objs);
        temp->rest = calcula_restricoes(nova_sol, grafo, objs, rests);
        temp->fitness = calcula_max(nova_sol, grafo, objs);
        temp->num = i;
        temp = temp->next;
    }
    return solucoes;
}

int* pesquisa_tabu(int sol[], int *grafo, int objs, int rests, int num_iter){
    int fitness, fitness_viz, i, memoria[objs*2/8];
    lista *solucoes, *temp;

    solucoes = malloc(sizeof(lista));
    temp = solucoes;

    for(i=1; i<objs; i++){
        temp->next = malloc(sizeof(lista));
    }
    temp->next = NULL;
    solucoes = gere_lista(solucoes, sol, grafo, objs, rests);
    return sol;
}

我正在尝试对我的学校作业执行禁忌搜索算法,但它并没有真正奏效。 此代码应该创建一个与 pesquisa_tabu 函数中的对象具有相同数量的链接的链表,然后它在邻居中生成相同数量的并为每个链接添加一个邻居,然后处理 pesquisa_tabu 中的所有信息功能。 而且我找不到这段代码有什么问题,它总是在第二次迭代时崩溃......

【问题讨论】:

  • 你的 for 循环是错误的,你只是将内存分配给同一个 temp->next 一遍又一遍,然后立即将其设置为 null
  • 寻求调试帮助的问题(为什么这段代码不起作用?)必须包括所需的行为、特定的问题或错误以及在问题本身中重现它所需的最短代码。没有明确问题陈述的问题对其他读者没有用处。请参阅:如何创建minimal reproducible example

标签: c pointers linked-list malloc


【解决方案1】:
for(i=1; i<objs; i++){
        temp->next = malloc(sizeof(lista));
    }
    temp->next = NULL;

您所做的是为objs 数量的lista 分配了内存并丢失了与所有这些的链接,因为您总是让temp-&gt;next 指向一个新内存,然后再让它指向@987654325 @.在为所有节点分配内存时,您需要维护列表的head

lista *solucoes, *temp;//solucoes will act as head of list    
temp = NULL;
solucoes = NULL;

for(i=1; i<objs; i++)
{
    if(solucoes==NULL)
    {
         temp = malloc(sizeof(lista));
         solucoes = temp;
    }
    else    
    {
        temp->next = malloc(sizeof(lista));
        temp = temp->next;
    }
}
temp->next = NULL;

【讨论】:

  • 我使用temp作为临时指针,主指针是solucoes,即使我使用临时指针我会丢失所有链接吗?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-07-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多