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?
CodePudding user response:
scanf
reads the string until it reaches whitespace or end of the input (thanks for the comment!), so you need to implement your function to read a string of unknown size. Byte by byte. Unlike Java, you can't read from stdin and check what it is without advancing past the input. Once the byte was read, you are responsible for remembering it if you need it later.\0
Take a look at that: How can I read an input string of unknown length?
FYI: with scanf
you can specify the length of the buffer you are writing to:
https://stackoverflow.com/a/12306624/7095554
The return value of scanf
:
RETURN VALUE
On success, these functions return the number of input items
successfully matched and assigned; this can be fewer than
provided for, or even zero, in the event of an early matching
failure.
The value EOF is returned if the end of input is reached before
either the first successful conversion or a matching failure
occurs. EOF is also returned if a read error occurs, in which
case the error indicator for the stream (see ferror(3)) is set,
and errno is set to indicate the error.
source: https://man7.org/linux/man-pages/man3/scanf.3.html#RETURN_VALUE