abhiram reddy
abhiram reddy

Reputation: 3

How to dynamically allocate string size according to user input in C?

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.

Upvotes: 0

Views: 1723

Answers (2)

Chris
Chris

Reputation: 36496

An alternative approach to shrinking the memory to the minimum needed for user input would be to allocate a second chunk of memory based on the size of the input, copy the string into it, then free the original.

We're just going to assume malloc and scanf worked as we meant them tto and not error check for the purposes of this answer.

char *s1 = malloc(1024);
scanf("%1023s", s1);

char *s2 = malloc(strlen(s1) + 1);
strcpy(s2, s1);

free(s1);

You might also use strdup.

Upvotes: 0

William Pursell
William Pursell

Reputation: 212238

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("%31s", s); 

Always check the value returned by malloc, realloc, and scanf.

Upvotes: 4

Related Questions