Menu
CoddyTech

Owned Copies and free

Lesson 33 of 48 in Coddy's C for R Developers course.

R character vectors behave like values. After copy <- original both names share the data only until one side is modified; then R copies it (copy-on-modify), and the garbage collector frees whatever is no longer referenced. A C API returning a writable copy must allocate storage whose lifetime outlives the function. Free exactly once after the last use; never return an address of a local array and never free a borrowed literal.

R

original <- "cat"
copy <- original
substr(copy, 1, 1) <- "X"
cat(original, ":", copy, "\n", sep = "")

C17

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stddef.h>
#include <stdbool.h>
#include <limits.h>
#include <errno.h>

int main(void) {
char original[]="cat";char *copy=malloc(sizeof original);if(!copy)return 1;memcpy(copy,original,sizeof original);copy[0]='X';printf("%s:%s\n",original,copy);free(copy);
return 0;
}

Porting rule

Document whether a returned pointer is owned or borrowed.

challenge icon

Challenge

Easy

Implement clone_text(text), returning an independently writable, malloc-owned, null-terminated copy. Return NULL on allocation failure. The driver changes the first copied byte to X when nonempty, prints original:copy, and frees the copy. Input is one ASCII line shorter than 128 bytes.

Edit the unlocked source and header files. Keep the declared public API compatible with the visible locked main.c, which calls it directly. Do not add another main. All numeric task fixtures are small enough to avoid overflow unless the task explicitly checks a range. Print only the specified output; the driver supplies input parsing and output when shown.

Try it yourself

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stddef.h>
#include <stdbool.h>
#include <limits.h>
#include <errno.h>
#include "lesson.h"
int main(void){char text[128]="";if(fgets(text,sizeof text,stdin))text[strcspn(text,"\n")]=0;char *copy=clone_text(text);if(!copy || copy==text)return 2;if(copy[0])copy[0]='X';printf("%s:%s\n",text,copy);free(copy);return 0;}
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in C for R Developers

Practice on your own: Online C compiler