#Overwriting memory on loop iteration

7 messages · Page 1 of 1 (latest)

onyx anvil
#

I am curious about the behavior of the following function:

void run_nfa(NFA *nfa, char *input, int *buf) {
  if (!nfa) return;
  int state[MAX_STATES];
  for (int i = 0; i < MAX_STATES; i++) state[i] = -1;
  int *cur_state = state;
  cur_state[0] = nfa->initial_state;
  for (int i = 0; input[i] != '\0'; i++) { // iterate over input
    int new_state[MAX_STATES];
    for (int j = 0; j < MAX_STATES; j++) new_state[j] = -1;
    int count = 0;
    for (int j = 0; j < MAX_STATES; j++) { // iterate over every current state
      if (cur_state[j] == -1) break;
      int temp[MAX_STATES];
      for (int k = 0; k < MAX_STATES; k++) temp[k] = -1;
      nfa->delta(cur_state[j], input[i], temp);
      for (int k = 0; k < MAX_STATES; k++) { // iterate over returned states
        if (temp[k] == -1) break;
        bool has_added = false;
        for (int h = 0; h < count; h++) { // iterate over states already added to new_state
          if (new_state[h] == temp[k]) {
            has_added = true;
            break;
          }
        }
        if (!has_added) new_state[count++] = temp[k];
      }
    }
    cur_state = new_state;
  }
  memcpy(buf, cur_state, MAX_STATES * sizeof(int)); 
}

Every loop iteration of the nested loops takes the current states and calculates new states based on the current input symbol.
The current behavior is that on every loop iteration starting from the second iteration, new_state[MAX_STATES] gets created at the same memory address and the memory pointed to by cur_state gets overwritten by the initialization loop that I have there for new_state.
I know that I can fix this by using memcpy(). I am just curious why this happens. I obviously have a pointer pointing to that memory address so why does it get overwritten? Is it because new_state belongs to previous loop scope instance so it gets deallocated and that memory address becomes a free real estate?

gusty oracleBOT
#

When your question is answered use !solved to mark the question as resolved.

Remember to ask specific questions, provide necessary details, and reduce your question to its simplest form. For tips on how to ask a good question use !howto ask.

buoyant night
#

Local variables die at the }

#

new_state will be at the same location every iteration in practice, but that's not guaranteed and you certainly can't rely on its contents until you've initialized it

onyx anvil
#

Thanks for clarifying

#

!solved