Since the calloc is only for the first allocation you cannot be sure of zero-termination with the reallocs. Best to store the '\0' yourself.
To determine the currently allocated size you cannot use strlen or sizeof. There is no standard way to do this. Instead, just keep track of the size yourself.
Since sizeof(char) is defined to always be 1, you may as well just say 1.
It is very old-fashioned to define a for-loop index variable outside of the for-loop head unless it is being used after the loop for some purpose.
In your case, the final realloc is pointless as it could only save you at most 31 bytes, although it can be useful to realloc downwards as this frees up memory for other allocations by the same program.
Coincidentally, your text, including the '\0', is divisible by 32.
Code:
#include <stdio.h>
#include <stdlib.h>
#define CHUNK 32
void *my_realloc(void *buffer, size_t size) {
char *tmp = realloc(buffer, size);
if (!tmp) {
perror("realloc");
free(buffer);
exit(1);
}
return tmp;
}
int main() {
const char *words =
"At vero eos et accusamus et iusto odio dignissimos ducimus qui"
"blanditiis praesentium voluptatum deleniti atque corrupti quos"
"dolores et quas molestias excepturi sint occaecati cupiditate"
"non provident, similique sunt in culpa qui officia deserunt"
"mollitia animi, id est laborum et dolorum fuga. Et harum quidem"
"rerum facilis est et expedita distinctio. Nam libero tempore,"
"cum soluta nobis est eligendi optio cumque nihil impedit quo"
"minus id quod maxime placeat facere possimus, omnis voluptas"
"assumenda est, omnis dolor repellendus. Temporibus autem"
"quibusdam et aut officiis debitis aut rerum necessitatibus"
"saepe eveniet ut et voluptates repudiandae sint et molestiae"
"non recusandae. Itaque earum rerum hic tenetur a sapiente"
"delectus, ut aut reiciendis voluptatibus maiores alias"
"consequatur aut perferendis doloribus asperiores repellat.";
int bufsize = CHUNK;
char *buffer = my_realloc(NULL, bufsize), *b = buffer;
for (const char *w = words; (*b++ = *w++); )
if (b - buffer == bufsize)
buffer = my_realloc(buffer, bufsize += CHUNK);
printf("%s\n", buffer);
printf("bufsize: %5d\n", bufsize);
printf("used : %5d\n", (int)(b - buffer));
free(buffer);
return 0;
}