#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX_NAME_LENGTH 32
int main()
{
char * name = (char *)(malloc(sizeof(char) * MAX_NAME_LENGTH));
strcpy(name, "John Doe");
printf("Hello, %s!\n", name);
free(name);
return 0;
}
- First, you allocate the memory with malloc(). Since it returns you a void *, you need to cast it to the right type (char * in our example).
- Then, you fill that memory with value. You absolutely cannot do name = "John Doe", because you'll loose track of your allocated memory (causing a memory leak) and later, when you'll try to free the memory, now it points to a location that was not allocated by you and thus, you must not deallocate it. So use strcpy() to fill the memory with string data.
- Then you use your variable (we simply print it in the example).
- Finally, you need to release the allocated memory with free().
I hope this gives you a good idea of how to deal with dynamic memory de/allocation in your C program.
Good luck!