Copying data between two struct pointers giving segmentation fault

user1452307 Source

I am getting a segmentation fault when trying to copy the contains of a pointer to a struct to another pointer.

My struct:

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;

Memory allocation method:

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

Here' an example of my Structs Alphabets

CANAMA
PANAL_

I have a randomize function that gives me the two possible moves of the state. The two moves for the above state would be

CANAM_
PANALA  
AND
CANAMA
PANA_L

In my randomize state function I copy the contains of my current state and then put it in the new state.

But here is the problem, I'm doing a breadth first search and trying to find out the shortest distance from the one state to another. In the process of doing I get pretty far in the search. But then it gives a segmentation fault at line where I copy the contains of current state to a new state. I tried memcpy as well, but it gives the same segmentation fault. Here are the lines:

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

So, is the way I am copying my memory incorrect that is causing the problem. But if thats the case then why does it go for a while and then gives out a segmentation fault. Please help.

Here's a link to my full code. Full Code

cstructsegmentation-faultmalloc

Answers

answered 5 years ago addaon #1

Looks like at least one of new_state and current_state is null. Best to change your printfs from printf("If exception below then problem in swapN\n"); to printf("If exception below then problem in swapN: %p %p\n", current_state, new_state1); to see where this happens; but at least one possibility is the following:

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); 

Notice that the second call to swap() will ALWAYS have new_state1 be NULL (because you already returned it if's not null!)

comments powered by Disqus