在两个结构指针之间复制数据会出现段错误

标签 c struct segmentation-fault malloc

当我尝试将结构体指针的内容复制到另一个指针时,出现段错误。

我的结构:

typedef struct State {
  char alphabets[2][6]; 
  struct State *PREV; /*this points to the previous state it came from*/
  struct State *NEXT; /*this points to the next state in the linked list*/
  int cost; /*Number of moves done to get to this position*/
  int zero_index;/*this holds the index to the empty postion*/
  char *move[2];/*this holds the move that was done to get to this state*/
} State;

内存分配方法:

State *memAllocator() {
  State *p = (State*)malloc(sizeof(State));
  if (p == NULL) {
    printf("Malloc for a new position failed");
    exit(1);
  }
  return p;
}

这是我的结构字母表的示例

CANAMA
PANAL_

我有一个随机函数,可以为我提供两种可能的状态移动。上述状态的两个 Action 是

CANAM_
PANALA  
AND
CANAMA
PANA_L

在我的随机状态函数中,我复制当前状态的内容,然后将其放入新状态。

但问题是,我正在进行广度优先搜索,并试图找出从一个状态到另一个状态的最短距离。在这样做的过程中,我在搜索中走得很远。但随后它在我将当前状态的包含内容复制到新状态的行中出现段错误。 我也尝试了 memcpy,但它给出了相同的段错误。以下是几行:

*new_state=*current_state;
/*memcpy(new_state, current_state, sizeof(State));*/

所以,是我复制内存的方式不正确导致了问题。但如果是这样的话,为什么它会持续一段时间然后给出段错误。请帮忙。

这是我的完整代码的链接。 Full Code

最佳答案

看起来 new_state 和 current_state 至少有一个为 null。最好将 printfs 从 printf("如果下面出现异常,那么 swapN\n 中出现问题"); 更改为 printf("如果下面出现异常,那么 swapN 中出现问题: %p %p\n", current_state, new_state1); 查看发生这种情况的位置;但至少有一种可能性如下:

printf("If exception below then problem in swap3\n"); 
new_state1 = swap(empty_index/10, (empty_index%10)-1,current_sta te, new_state1); 
printf("If this prints problem not in swap\n"); 
if (new_state1 != NULL){
    //... [REMOVED FOR CLARITY]
    return; 
} 
/*Go East*/ 
/*printf("Step %d, move %c west\n",current_state->alphabets[empt y_index/10][(empty_index%10)+1]);*/ 
printf("If exception below then problem in swap4\n"); 
new_state1 = swap(empty_index/10, (empty_index%10+1),current_state, new_state1); 

请注意,对 swap() 的第二次调用将始终使 new_state1 为 NULL(因为如果不为 null,则您已经返回了它!)

关于在两个结构指针之间复制数据会出现段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13903323/

相关文章:

C++ 如何将百万个对象存储到数组中而没有段错误

c - 将文本文件的每一行转换为数组 c

c - C 上的链表返回 NULL

c - 将结构成员保存到 C 中的 .txt 文件时出现意外结果

c - 访问结构中的结构指针时出现段错误

c++ - 用 Python+ctypes、segfault 包装 C++ 动态数组

c - 为什么 Valgrind 提示 fgets?

c - 用于大小分析的 GCC 工具?

c++ - 如果我在 C 或 C++ 中执行 `typedef`,我什么时候应该在 typedef'ed 类型的末尾添加 `_t`?

c++ - 结构中的 vector - 最佳方法? C++