Hello, welcome back. This will be our last assignment, our last challenge for
our pointer section.
In this challenge, I want you to understand
how dynamic memory allocation works. So you're going to need to malloc a string.
It's going to be pretty basic.
But it will get you understanding
this whole concept of dynamic memory allocation.
What are the advantages of dynamic memory allocation?
Well, it means that you can allocate enough memory when you need it.
You don't have to waste memory. And if you need more memory you can re-allocate.
This assignment just going to have you using malloc.
So in this challenge, you're going to write a program that tests your understanding of dynamic memory allocation.
I want you to write a program that allows the user to input a text string.
So you're going to need to use scanf. You can also use git s,
we haven't talked about it a ton, but git s or f git s
on the standard input stream will allow you to
read a string that contains spaces. Remember, scanf
it's only going to read the string up to a space.
If you use git s, you can read multiple strings separated by spaces,
either way is fine though, scanf or git s either way.
You're going to have the user enter a string. The program is going to print
the text that was inputted.
That may seem very easy, but the difference here is that the program is going to utilize
dynamic memory allocation.
You can also have the user enter the limit of the string they are entering,
and then you can use that for malloc, so you know how many bytes to allocate.
You should create a char pointer, only a character pointer, no character arrays.
I want you to allocate memory. Remember, when you create the character array,
the memory is automatically already allocated for you based on what the
size that you put in
to the brackets. And again, a big disadvantage of that is now what if
you try to enter something larger than what you put in the size, you have to recompile.
It's static. That memory gets allocated at compile time.
Dynamic memory gets allocated when you're running the program.
And so you can determine how much memory you want to allocate based on what the user enters.
So again, ask the user to enter a number
for the number of bytes you want to allocate for the string.
Then ask the user to enter the string in.
And you have to correctly allocate memory and then pass that character pointer into scanf
or git s
and then basically just display the text that was entered.
And then lastly, do not forget about the all important free function.
You always want to release your memory when you're done using it
and you want to make sure you do that so that other programs
can utilize that memory. Memory is a scarce resource,
especially on embedded systems real-time programs,
so don't hog the memory, release it.
Good luck, and I'll provide a solution in the next lecture. Thank you.