讨论/技术交流/对于指针未对齐问题的处理/
对于指针未对齐问题的处理

可以问一下这个报错内容应该怎么处理呢?

百度了很久,也没能收获到比较清晰的解释··· 所以来此向各位大神求救,希望得到帮助!🙏

Line 23: Char 9: runtime error: load of misaligned address 0xbebebebebebebebe for type 'struct Node *', which requires 8 byte alignment (solution.c)
0xbebebebebebebebe: note: pointer points here
<memory cannot be printed>

下面是我初学DFS算法写的代码(题目:克隆图)。还在调试阶段,然后了遇到上面这个报错...

/**
 * Definition for a Node.
 * struct Node {
 *     int val;
 *     int numNeighbors;
 *     struct Node** neighbors;
 * };
 */

bool whetherVisited(int* visited, int visitNum, int test){
    for(int i=0; i<visitNum; i++)
        if(test==visited[i]) return 1;
    return 0;
}

void DFS(struct Node *s1, struct Node *s2, int* visited, int visitNum){
    s2->val = s1->val;
    visited[visitNum++] = s1->val;
    s2->numNeighbors = s1->numNeighbors;
    for(int i=0; i<s1->numNeighbors; i++){
        if(whetherVisited(visited, visitNum, s1->neighbors[i]->val)) continue;
        struct Node* next_neighbor = (struct Node *)malloc(sizeof(struct Node));
        DFS((s1->neighbors)[i], (s2->neighbors)[i], visited, visitNum);
    }
}

struct Node *cloneGraph(struct Node *s) {
    int visitNum=0;
    int* visited = (int *)malloc(sizeof(int)*100000);
    struct Node * graph = (struct Node *) malloc (sizeof(struct Node));
    DFS(s, graph, visited, visitNum);
    return graph;
}

共 1 个回复

你是不是少申请了内存?我想想
你s2的neighbors内存哪来的?

解释一下
struct Node** neighbors;
是一个指针数组指针
初始化时只有一个4位/8位的指针
你需要申请一片numNeighbors长度的Node*指针数组,然后在里面存指向Node的指针
然后你next_neighbor是干什么的?为什么要申请这个?你所有节点不是应该存在graph里吗?

1