Tsallaka zuwa abun ciki
Justice Tech School

Dynamic Strings

Allocate length + 1 for the terminator. strdup style copy.

Example
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main(void) {
  const char *src = "hello";
  char *s = malloc(strlen(src) + 1);
  strcpy(s, src);
  s[0] = 'H';
  printf("%s\n", s);
  free(s);
  return 0;
}

Result

Hello

Exercise

Space for the terminator.

strlen(s) + 

Quiz Test

Why + 1?

These free lessons are for learning. Join a full course for projects, mentor feedback and a verified certificate.