【问题标题】:Copying data between two struct pointers giving segmentation fault在两个结构指针之间复制数据导致分段错误
【发布时间】:2012-12-03 21:49:15
【问题描述】:

尝试将指向结构的指针的包含内容复制到另一个指针时出现分段错误。

我的结构:

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_

我有一个随机函数,它给了我两个可能的状态移动。上述状态的两个动作将是

CANAM_
PANALA  
AND
CANAMA
PANA_L

在我的随机状态函数中,我复制当前状态的包含,然后将其置于新状态。

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

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

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

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

【问题讨论】:

  • 您可能正在访问一些已经被释放的内存,或者您正在访问一些未初始化的内存 - 很可能 current_state 或 new_state 没有指向段错误点的良好内存位置.我建议使用 valgrind 来解决这个问题。
  • 感谢 valgrind 的推荐。我试试看!

标签: c struct segmentation-fault malloc


【解决方案1】:

看起来 new_state 和 current_state 中至少有一个为空。最好将您的 printfs 从 printf("If exception below then problem in swapN\n"); 更改为 printf("If exception below then problem in 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,那么第二个交换将不是 null,而是一个不在 hash_table 中的随机状态。我只想要 new_state1 中的一个状态,所以如果我在第一次交换中没有得到 null,我就使用了 break。
  • 但是您正在使用 new_state1,您刚刚将其写入 NULL,作为 swap 的参数,而不仅仅是用于输出。
  • 是的,我将一个 null new_state1 作为参数传递给 swap,因为它在方法 swap 内部,我将 current_state 的值填充到 new_state 并在 new_state 中进行一些进一步的更改。然后 swap 方法检查状态是否在 hash_table 中,如果不是,则返回现在已填充数据的 new_state,如果是则返回 NULL。
  • 很公平。我仍然建议在崩溃时检查(通过printf)实际的指针值——段错误意味着你正在取消引用非法值(在赋值的一侧或另一侧),到目前为止最有可能的非法值是NULL.
  • 所以,这是我在分段错误之前得到的指针输出如果下面的异常则交换中的问题:0x10c703900 0x0 似乎 new_state1 指向 0x0,我认为它是 NULL
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-02-20
  • 1970-01-01
  • 2018-07-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-06-11
相关资源
最近更新 更多