rotcod
rotcod

Reputation: 13

Heap error when reallocating the 14th time

Note: only C, VisualStudio 2017 for didactic exercise I cannot use [] for accessing pointers and have to use fgetc().

It's a simple program to convert a string received in command line into the same in capital letter. When i have to realloc >= 14 bytes the debug trigger a breakpoint with the following error: "invalid address specified to RtlValidateHeap".

Here:

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


int main(void) {

    char c;
    size_t size_input = 1, allocatedMem=1;
    char *input = malloc(size_input);
    while (1) {
        c = fgetc(stdin);
        if (c == '\n') {
            realloc(input, size_input);
            *(input + size_input - 1) = 0;
            break;
        }
        ++size_input;
        if (allocatedMem < size_input)
        {
            allocatedMem *= 2;
            realloc(input, allocatedMem);
        }
        *(input + size_input - 2) = toupper(c);
    }

    free(input);
    return 0;
}

But also here:

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


int main(void) {

    char c;
    size_t size_input = 1;
    char *input = malloc(size_input);
    while (1) {
        c=fgetc(stdin);
        if (c == '\n'){
            *(input + size_input - 1) = 0;
            break;
        }
        ++size_input;
        realloc(input, size_input);
        *(input + size_input - 2) = toupper(c);
    }

    free(input);
    return 0;
}

always when the second argument of realloc() is a number >= 14. Where am I wrong?

Upvotes: 1

Views: 45

Answers (1)

chux
chux

Reputation: 154315

Save the result of realloc().

// realloc(input, allocatedMem);
void *ptr = realloc(input, allocatedMem);
if (ptr == NULL) {
  fprintf(stderr, "Out of memory\n");
  exit(EXIT_FAILURE);
}
input = ptr;

Also

// char c;
int c;

      // if (c == '\n') {
      if (c == '\n' || c == EOF) {

Upvotes: 3

Related Questions