I am trying to work with dynamically allocated string inputs in C, such that it will reallocate memory realloc()
once the inputted string exceeds the previously allocated memory instead of going into an undefined behavior
This is my code:
#include <stdio.h>
int main() {
char *text, *retext;
text = malloc(10 * sizeof(*text));
scanf("%s", text);
if(text == NULL) {
printf("\nTry Again: ");
retext = realloc(text, 20 * sizeof(*retext));
scanf("%s", retext);
printf("\n%s", retext);
free(retext);
retext = NULL;
}
printf("\n%s", text);
free(text);
text = NULL;
}
I basically want to run realloc() if the text's length exceeds 10 (including \0). I later learnt from many Stackoverflow answers that malloc() doesn't really return NULL and instead goes into "Undefined Behavior" and everything will seem to work even after exceeding 10chars. However, I want somehow to be able to "detect" when malloc() is starting this Undefined behavior, and jump to the realloc() block instead of proceeding any further. How do I achieve that?