If i input too many characters my program either has a 'mremap_chunk(): invalid pointer' or a 'realloc(): invalid old size'

Viewed 67

my program was built as a test to input as many sentences as the user want (until he enters -1), and then concatenate all sentences (\n included). If i input some characters is fine, but if i input more then 25 characters i have the two errors listed above, i tried simulating what would happen in paper and i can´t find the problem, help is appreciated, thanks in advance.

The code is displayed below:

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

int main(void)
 {
  char *s = malloc(1), *sentence = malloc(0);
  int sSize = 0;
  
  printf("Insert sentences, press '-1' if you want to exit:\n");
  
  do
  {
    fgets(s,100,stdin);
    if(strcmp(s,"-1\n") != 0)
    { 
      sSize += strlen(s);
      sentence = realloc(sentence, sSize * sizeof(char));
      //s[strcspn(s, "\0")] = '\n';
      strcat(sentence, s);
    }
  }while(strcmp(s,"-1\n") != 0);

  printf("==================sentence================\n");
  printf("%s", sentence);
  return 0;
}
2 Answers

This is a classic buffer overrun problem:

s = malloc(1) - s now points to a one-character buffer.

fgets(s,100,stdin); - reads up to 100 characters into s - which is a one-character buffer.

EDIT

Here's a version which works and doesn't use a separate "sentence buffer":

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

int main(void)
  {
  const char *terminator = "-1\n";
  char *sentences = malloc(100);
  char *pNext_sentence;

  printf("Insert sentences, press '-1' if you want to exit:\n");

  *sentences = '\0';

  do
    {
    sentences = realloc(sentences, strlen(sentences)+100);

    pNext_sentence = sentences + strlen(sentences);

    fgets(pNext_sentence, 100, stdin);
    } while(strcmp(pNext_sentence, terminator) != 0);

  *(sentences + (strlen(sentences) < strlen(terminator) ? 0 : strlen(sentences) - strlen(terminator))) = '\0';

  printf("==================sentences================\n");
  printf("%s", sentences);

  free(sentences);

  return 0;
  }

You must use reallocate memory with realloc before using fgets, which, in your case, reads 100 bytes. Your string has the initial size of 1.

Related