Question

Im doing some test for a larger program, here im trying to move a blank inside a char array full of '*', it work fine but after sending many key the value of left and right key change, I dont get why

Here is my code:

include <curses.h>
//#include <term.h>                                                                                              
#include <termios.h>
#include <stdlib.h>
#include "includes/my_list.h"

void                    init_term()
{
  struct termios        term;

  if (tcgetattr(0, &term) != 0)
    {
      printf("Fail to get input termios\n");
      //      return(0);                                                                                         
    }
  term.c_lflag &= ~(ICANON | ECHO);
  term.c_cc[VMIN] = 1;
  term.c_cc[VTIME] = 0;
  if (tcsetattr(0, TCSANOW, &term) != 0)
    {
      printf("Fail to set input termios\n");
      //      return(0);                                                                                         
    }
}

t_info          change_dir(t_info info, int flag)
{
  if(flag == 0)
    info.pos++;
  else if (flag == 1)
    info.pos--;
  info.tab[info.pos] = ' ';
  return(info);
}

int             main()
{
  int           c;
  int           i;  int           pos;
  t_info        info;

  //  tgetent(NULL, "xterm");                                                                                    
  info.tab = malloc(sizeof(*info.tab) * 10);
  i = 0;
  info.pos = 0;
  init_term();
  while (read(0, &c, sizeof(int)) != 0)
    {
      printf("c = %d\n", c);
      //      sleep(1);                                                                                          
      while(i < 9)
        {
          info.tab[i] = '*';
          i++;
        }
      i = 0;
      if(c == 4479771)
        {
          printf("left ok1\n");
          info = change_dir(info, 1);
        }
      else if (c == 4414235)
        info = change_dir(info, 0);
        printf("%s\n", info.tab);
    }
}
Was it helpful?

Solution

I think you mean info.tab to to be a pointer to a char string, so you should have
info.tab = malloc(sizeof(char) * 10);

Your version will allocate more memory that is necessary to hold 10 chars, but that shouldn't stop it working.

Also, change_dir() may set the index into this array to be outside the memory allocated to it (e.g. index of -1), which could have dire consequences.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top