[Solved] Deciding how much memory to dynamically allocate based on user input


Here is a description of malloc().

It takes a parameter size, in bytes.

So if the user entered 5 words, then you need to first allocate an array big enough to store 5 pointers.

Eg.

char ** words = NULL;
words = malloc(sizeof(char *) * <NUMBER OF CHARACTERS THE USER ENTERED>);

If we assume ASCII is being used and a character is a char, then each letter in each of the words is a byte. We also need to account for any spaces, line feeds, perhaps a carriage return, and a trailing null.

So how many letters are in a word? IDK, that’s up to you. But if we assume that “Supercalifragilisticexpialidocious” from Mary Poppins in the longest word we will encounter, then we need to allocate at least 34 characters, plus an extra for a trailing null terminator. So that leaves us with up to 35 bytes per word.

This will work:

enum { MAX_WORD_SIZE = sizeof("Supercalifragilisticexpialidocious") };

This will also take into account the trailing \0 – MAX_WORD_SIZE will be 35.

char * temp_word = NULL;
temp_word = malloc(MAX_WORD_SIZE);

To create all of your other word arrays you’d need to do something similar in a loop:

for(int i = 0; i< <NUMBER OF WORDS THE USER ENTERED>; i++)
{
    words[i] = malloc(MAX_WORD_SIZE);
}

To convert the number of words entered by the user into an integer you should use atoi()

After this you could use getchar() to pull the string from stdin one character at a time and manually place them into temporary you allocated, stopping when you get to a ' ' space.

To copy the temporary array into one of your word arrays you can use strcpy(), just ensure your temporary array always has a trailig \0 after the word.

Don’t forget to free() that pointer when you’re done.

I am assuming you are doing this for some sort of a homework assignment on dynamic memory and that is why your application is defined the way it is. But if you aren’t you should consider just reading the input into one buffer first using fgets() and using strtok() to split the string after its been read. That approach will take more memory but it would be cleaner.

Another thing you should consider doing is using calloc() instead of malloc() to do your allocation, that way you can ensure that all of your arrays are initialized with 0’s – it could save you from some confusion later on if there is garbage data already in those arrays.

Yet another thing to think about: The temporary array in this example can be allocated automatically or statically using temp_word[MAX_WORD_SIZE]; since I used an enum to store MAX_WORD_SIZE as a constant. There is no direct need to use malloc for this.

0

solved Deciding how much memory to dynamically allocate based on user input