문제

I'm new @programming and i have the following question: My Programm start an command prompt: like

input>

Then the user enters an string, a command like merge xyz.txt I've finally got it to run, that my programm only reads from the start to the space. So

printf("%s", command);

output: merge

If the user enters a string, where the command isnt' a command or theres no value it should start again printing input> and also after a command is done, it should print input> again. I tried to put all the stuff into a while loop:

void cmdLine()
{
  char *whole_entrie = calloc(1,1);
  char buffer[BUFFERSIZE];
  int dummy = 0;
  while(dummy == 0)
  {
    printf("input>");
    fgets(buffer, BUFFERSIZE, stdin);
    whole_entrie = realloc(whole_entrie, strlen(buffer) + 1);
    strcpy(whole_entrie, buffer);
    strcpy(buffer, ""); //reset because i thought the programm uses old entries?????ß

    int cnt = 0;
    char command[MAX_COMMAND_LENGTH];

    while(cnt <= MAX_COMMAND_LENGTH)
    {
      if(whole_entrie[cnt] == ' ')
      {
        break;
      }
      else
      {
        command[cnt] = whole_entrie[cnt];
        cnt++;
      }
    }

    if(strcmp(command, "merge") == 1)
    {
      merge();
    }
    else if(strcmp(command, "close") ==1)
    {
      free(whole_entrie);
      dummy = 1;
    }

BUT: It randomly does something else. Somtimes I get an double free error, or he is returning 0 or it shows the printf() of merge when i put in xxxkdlf and so on, can somebody help me please, I'm getting depressed about this damn code!!!

Greetings

도움이 되었습니까?

해결책

Why are you using realloc() at all? I don't see here any reason for dynamic allocation. Why can't you just process buffer content?

In accordance to C99 standard:

7.19.7.2 The fgets function Synopsis

...

The fgets function reads at most one less than the number of characters specified by n from the stream pointed to by stream into the array pointed to by s. No additional characters are read after a new-line character (which is retained) or after end-of-file. A null character is written immediately after the last character read into the array.

Yet another point. Why so strange memcmp() calls? From man memcmp:

The strcmp() and strncmp() functions return an integer less than, equal to, or greater than zero if s1 (or the first n bytes thereof) is found, respectively, to be less than, to match, or be greater than s2.

OK, finally (maybe) third. You check for space ('') inside whole_entrie to stop. But if you just enter command with '\n' at the end you will copy it including '\n' so strcmp() will fail to check your command.

다른 팁

While you are realloc()-ing, the address of the realloc-ed memory area can change. But you don't assign this change to the variable whole_entrie. Here is the problem:

input = realloc(whole_entrie, strlen(buffer) + 1);
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top