CodeBlanks Logo Icon CodeBlanks

Dynamic strings

  • C course
  • Intermediate
  • Lesson 18/116
  • 5 min

Learn to create dynamic strings with malloc.

Dynamic strings

A dynamic string is a char array allocated at runtime with malloc. Unlike fixed-size char arrays, its size is decided at runtime.

Example: char *s = malloc(20);. This allocates 20 bytes and assigns the start address to s. To fill the string use strcpy(s, "Merhaba");. malloc needs <stdlib.h>, strcpy needs <string.h>. When done, free it with free(s);; otherwise a leak occurs.

Using a dynamic string

Once allocated, a dynamic string is used like a normal string. It's filled with strcpy, printed with printf. The key is not to exceed the allocated size.

Example: char *s = malloc(20); strcpy(s, "Merhaba"); printf("%s\n", s); free(s);. Here 20 bytes are allocated, 8 are used (Merhaba + null). The remaining 12 are unused. malloc doesn't initialize; so filling with strcpy is important. The free call prevents a leak.

Practice Create and print a dynamic string

Allocate a twenty-byte dynamic string with char *s = malloc(20);. Fill it with strcpy(s, "Merhaba");. Print it with printf("%s\n", s);. Finally free it with free(s);. Include <stdlib.h> and <string.h>.

Starter code

main.c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

// Allocate 20 bytes with malloc
// Copy "Merhaba" with strcpy
// Print with printf, free with free

int main(void) {
    return 0;
}

Sample solution

main.c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main(void) {
    char *s = malloc(20);
    strcpy(s, "Merhaba");
    printf("%s\n", s);
    free(s);
    return 0;
}

Expected output

Merhaba

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Which function is used for a dynamic string?

  • malloc Correct answer
  • printf
  • strcmp
  • strlen

Explanation: malloc allocates heap memory for a dynamic string.

2 Allocate a dynamic string

Question
char *s = ____(20);
strcpy(s, "Merhaba");
Answer
char *s = malloc(20);
strcpy(s, "Merhaba");

Explanation: malloc(20) allocates twenty bytes of dynamic memory.

3 Match the dynamic string parts

Term Meaning
malloc(20) Allocation
strcpy(s, ...) Filling
printf("%s", s) Printing
free(s) Release

All lessons in Intermediate