0

構造体へのポインターの内容を別のポインターにコピーしようとすると、セグメンテーション違反が発生します。

私の構造体:

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_

状態の2つの可能な動きを与えるランダム化機能があります。上記の状態の 2 つの動きは次のようになります。

CANAM_
PANALA  
AND
CANAMA
PANA_L

私のランダム化状態関数では、現在の状態の内容をコピーしてから、新しい状態に置きます。

しかし、ここに問題があります。幅優先検索を行って、ある州から別の州への最短距離を見つけようとしています。その過程で、私は検索でかなり遠くまで行きます。しかし、その後、現在の状態の内容を新しい状態にコピーする行でセグメンテーション違反が発生します。memcpy も試しましたが、同じセグメンテーション違反が発生します。ここに行があります:

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

それで、問題を引き起こしているのは、メモリを正しくコピーしていない方法です。しかし、そうであれば、しばらくするとセグメンテーション違反が発生するのはなぜですか。助けてください。

ここに私の完全なコードへのリンクがあります。完全なコード

4

1 に答える 1

0

new_state と current_state の少なくとも 1 つが null のようです。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);これがどこで発生するかを確認することをお勧めします。しかし、少なくとも 1 つの可能性は次のとおりです。

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() への 2 番目の呼び出しでは、常に new_state1 が指定されることに注意してNULLください (null でない場合は、既にそれを返しているためです!)

于 2012-12-16T16:54:49.353 に答える