简体   繁体   中英

Losing Value of Variable - C

  • Compiler:gcc 4.5.2
  • Terminal:Xterm
  • OS:Linux(x86)
  • Ncurses 5.9

I am programming a text editor that uses ncurses to graphicaly represent an array key_strokes[] . It is one dimensional so I use the macro INDEX(y*maxx+x) to point to the current position in key_strokes ( key_strokes[INDEX] ). y and x are the current coordinates in the terminal returned by the function getyx(stdscr, y, x) and maxx is the max amount of cols that can be in each row returned by the function getmaxyx(stdscr, maxy, maxx) . The program works great until I press backspace, for some reason the value of maxx is set to zero after it reaches the switch below. This of course throws off INDEX limiting it to only the first "row" of the array.

The user's key strokes are captured as int key_strokes . I use a switch case to check and see if it is an arrowkey, backspace, F12, etc. INDEX and maxx are defined as,

#define INDEX (y*maxx+x)
unsigned int maxx = 0;

Note I am also using cbreak(); noecho(); keypad(stdscr, TRUE); cbreak(); noecho(); keypad(stdscr, TRUE); .

case KEY_BACKSPACE:
if (INDEX >= 0)
{
   for(i = INDEX; key_strokes[i] != '\0'; i++) {
   key_strokes[i] = key_strokes[i+1];
   }

   if (total_count > 0) {
   total_count--;
   }

   delch();
   if (x == 0) {
   move(y-1, maxx-1);
   }
   else {
   move(y, x-1);
   } refresh();
}
break;

Are you sure that key_strokes[] is null terminated?

'cause if it isn't, the for loop will copy everything in memory to the previous cell, until it reaches 0. And if maxx or maxy are right before a 0 value, they will be set to 0.

Imagine the following layout:

| key_strokes[0] | key_strokes[...] |   key_strokes[n] | maxy | maxx | some_other_var |
|            'v' |              'i' | non-null garbage |   23 |   80 |           '\0' |

After pressing backsapce after 'i', it will be:

| key_strokes[0] | key_strokes[...] |   key_strokes[n] | maxy | maxx | some_other_var |
|            'v' | non-null garbage |               23 |   80 | '\0' |           '\0' |

That could also explain why it's maxy which is set to 0 when maxx is declared const (GCC doesn't store the const s at at the same place in memory).

To ensure that key_strokes[] is null-terminated, I'd suggest you to add this into your init section:

memset(key_strokes, 0, sizeof(char) * size_of_key_strokes_array);

I can't see the type of x and y (ie. signed or unsigned), but it seems interesting that you calculate (y times an unsigned integer and add x). What may be the type of this expression? Probably it depends on the type of y. Is it reasonable to check if it's greater than or equal zero in the condition? (Unsigned values are always gte zero...)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM