1

when I cannot figure out the issue with my code. The goal of the program is to read words from a text file and add them to a linked list. When I run this:

static char *make_string(char buffer[], int length) {
      char *str = (char *)(malloc(length+1));
      memcpy(str, buffer, length);
      str[length + 1] = '\0';
      return str;
    }

char *words_next_word() {
  char buf[MAXBUF] = {0};

  int character = getchar();
  int index = 0;
  static int count = 0;
  printf("it is the %d word \n", count);
  count++;

  while(isalnum(character) == 0){
    character = getchar();
  }

  while(character != EOF && isalnum(character) != 0){
    buf[index] = character;
    index++;
    character = getchar();
  }

  return make_string(buf, index);
}

After getting the word from the text file, I add it to a linked list. After adding the word, I free the string. The first 138 words are read and freed without issue. For some reason, the program crashes when trying to read the 138'th word, but I don't know why.

Bob Flanders
  • 35
  • 1
  • 6

1 Answers1

0

The first 138 words are read and freed without issue.

Not really. The problem exists even in the first make_string() call.


Code is attempting to duplicate the string yet has a off-by-one error.

static char *make_string(char buffer[], int length) {
      char *str = (char *)(malloc(length+1));  // size good
      memcpy(str, buffer, length);             // copy OK
      str[length + 1] = '\0';     // null character assigned in wrong place, 1 too far out
      return str;
    }

Assigning data in the wrong place (assigning out of bounds @EOF) and not defining the value of str[length] with a null character (and later using it) results in undefined behavior.

Here is a strdup() function, yet I suggest trying to code repair your make_string() before reviewing.


The below code does not limit writing to buf[]

while(character != EOF && isalnum(character) != 0){
    if (index + 1 >= MAXBUF) {
      puts("Too long");
      return NULL; // or some other error handling
    }
    buf[index] = character;
Community
  • 1
  • 1
chux - Reinstate Monica
  • 143,097
  • 13
  • 135
  • 256