on googling i got an answer but i am not able to understand how it works. I have just started coding so i hope someone could explain the code clearly for me.
char *s;
s = malloc(1024 * sizeof(char));
scanf("%s", s);
s = realloc(s, strlen(s) 1);
Thank you in advance.
CodePudding user response:
char *s;
s = malloc(1024 * sizeof(char));
The above declares the variable s
and assigns to it the address of a dynamically allocated chunk of memory large enough to hold 1024 chars. However, no error checking is performed, so s
may be NULL at this point.
scanf("%s", s);
This reads data from the input stream until a whitespace is encountered (or input terminates) and stores it in the allocated chunk of memory whose address is contained in s
, appending a '\0' after the data that is read. If there is more than 1023 bytes of data or if the previous malloc
returned NULL, undefined behavior occurs. (This is bad.)
s = realloc(s, strlen(s) 1);
This is an attempt to shrink the amount of memory being used so that s
now points to a smaller chunk of memory which is just big enough to hold the string that was read. The 1
is in the 2nd argument to realloc
because C stores strings as null terminated arrays, and it takes an extra character to store that terminator. This is possibly a memory leak, since realloc
can return NULL, in which case the original memory is lost and the program hasn't stored that value anywhere so cannot free it.
Do not ever use "%s"
in a call to scanf. If you have allocated N bytes for an array, use a width modifier of N - 1. Often this means dynamically generating the format string, but often it is as simple as:
char s[32]; scanf("1s", s);
Always check the value returned by malloc
, realloc
, and scanf
.