简体   繁体   中英

Using realloc to increase the size of an array

I am trying to scan a bunch of characters into an array. I have used malloc to set the original size of the array, but I want to use realloc to increase the size if the user enters more characters than the initial size allows. I am not quite sure where to put the realloc, or if it should be within a conditional statement.

char *strscan(void) {
  int size = sizeof(char) * 10;
  char *a = malloc(size);

  // Below I try to read character input from the user and store it in the array.

 while (a != EOF) {

    scanf("%c", a);
    if (trace) printf("%c", *a);
    ++a;
    a = realloc(a, 2 * size);
 }

    return a;

}

As of now I still get heap buffer overflow upon entering, for example, 15 characters.

++a;
a = realloc(a, 2 * size);

This is the problem. The first argument of realloc must be a pointer that is returned by the malloc family functions, or a null pointer. a used to be one, but by ++a; , it's not any more.

I see two problems here.

The first is that you're incrementing a , then passing the incremented value to realloc . Since the pointer passed to realloc was not a value returned from malloc , calloc , or realloc , or is NULL, this can cause errors.

The second problem is that you're not increasing the size of your memory buffer after the first call to realloc , since you're always passing it 2 * size and size never changes. So you eventually run past the end of the buffer.

You need a separate pointer to keep track of where the next character should go, and you need to keep track of how big your buffer currently is and realloc only when your existing buffer is almost full.

char *strscan(void) {
  size_t size = sizeof(char) * 10;
  char *a = malloc(size);
  char *current;  // The current character
  ptrdiff_t diff;

  current = a;
  do {
    scanf("%c", current);
    if (trace) printf("%c", *current);
    if (current - a >= size - 1) {
      size *= 2;
      diff = current - a;
      a = realloc(a, size);
      current = a + diff;   // Since "a" could change, we need to modify "current" as well
    }
  } while (*current++ != '\n');
  *current = '\x0';

  return a;
}

Remove that ++a . It is the culprit here .

realloc() accepts the either the NULL pointer or the malloc returned pointer.

Read from the man page.

Hope you understand . Happy Coding..

You need two pointers. One is the location of the buffer. The other is the location of the current character. When the difference between them is large enough, reallocate the buffer and reset the pointers.

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