This code is from a problem in HackerRank (Q: Printing Tokens in C).
#include <stdio.h> #include <string.h> #include <stdlib.h> int main() { char *s = malloc(1024 * sizeof(char)); // Allocate for string scanf("%[^\n]", s); s = realloc(s, strlen(s)+1); // Here's my doubt // Solution return 0; } Forget about the question, look at the following iteration-
s = realloc( s, strlen(s)+1 ); // +1 This line of code reallocates the memory of the string 's' according to the length of the string 's', It also increases the length for a null terminator '\0'. But strlen() only measures until it reaches '\0', but there's no '\0' in 's' as we're adding a byte for '\0'. How can we assume it will measure the perfect length of string 's'? If it measures the perfect length of 's' then there must be a null terminator at the end so why add 1 again?
Someone explain this, there's no null terminator '\0' so we add a byte for it.
Or Am I completely wrong about this?
scanfputs it there after the last input character. Otherwise it would not be a string in C at all. Thatrealloccall can only be used to reduce the size of the buffer. It cannot increase it that way.#include <math.h>for this text processing challenge?