Too many realloc calls?

1

I have the following C code:

char* str = (char*)malloc(sizeof(char));
int count = 0;

while ((c = getchar()) != EOF){
    str[count] = c;
    count++;
    str = (char*)realloc(str, sizeof(str) + sizeof(char));
}

But it is throwing the error Unhandled exception at 0x77C8F94D (ntdll.dll) in algorithms.exe: 0xC0000374: A heap has been corrupted. I have been trying to solve this for ages, but can't get it right. Interestingly, it is only an issue when the input stream has a large number of characters to be read.

Is this due to my usage of malloc and realloc?

c
asked on Stack Overflow Sep 22, 2019 by Harry Stuart • edited Sep 22, 2019 by ggorlen

1 Answer

3

Corrected code below:

char* str = (char*)malloc(sizeof(char));
int count = 0;

while ((c = getchar()) != EOF){
    str[count] = c;
    count++;
    str = (char*)realloc(str, count * sizeof(char));
}

However, this does use too many realloc calls! Better to only allocate in blocks, where I've also used the BPC principle, rather than MNC (see comments):

size_t limit = 1024u; // For example!
char* str = malloc(limit);
int count = 0;
while ((c = getchar()) != EOF) {
    str[count] = c;
    if (++count >= limit) {
        limit += 1024u;
        char *str2 = realloc(str, limit); // Shouldn't use same pointer ...
        if (!str2) { // ... failure!
            // <Some error message/flag>
            break;
        }
        else str = str2; // Successful realloc
    }
}
answered on Stack Overflow Sep 22, 2019 by Adrian Mole • edited Sep 22, 2019 by Adrian Mole

User contributions licensed under CC BY-SA 3.0