Menu
CoddyTech

Growing Without Losing Data

Lesson 34 of 48 in Coddy's C for Swift Developers course.

Swift's append grows an array's buffer for you, and because Swift code reaches elements through the array and its indexes (a pointer from withUnsafeMutableBufferPointer is valid only inside its closure), moving the buffer cannot leave a dangling alias. C realloc has no such guard: success may move the block and invalidate every old pointer into it, while failure returns NULL and leaves the original block owned by the old pointer.

realloc can move storage. Preserve the original pointer until success; aliases may become invalid after a successful call.

Swift example

var values = [2, 4]
values.append(6)
print(values[2])

Swift output:

6

C example

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

int main(void) {
int *values=malloc(2*sizeof *values);if(!values)return 1;values[0]=2;values[1]=4;int *grown=realloc(values,3*sizeof *values);if(!grown){free(values);return 1;}values=grown;values[2]=6;printf("%d\n",values[2]);free(values);
return 0;
}

C output:

6
challenge icon

Challenge

Easy

First input integer is the new value; remaining up to 16 integers are the existing sequence. append_value(data,count,value) appends if count is below 16. On capacity rejection or allocation failure return false and preserve pointer, count and contents. On success transfer the grown allocation through *data and increment *count. Driver verifies old elements and prints count:last, or full:count.

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){int value;if(scanf("%d",&value)!=1)return 1;int old[16];size_t n=0;while(n<16 && scanf("%d",&old[n])==1)n++;int *data=n?malloc(n*sizeof *data):NULL;if(n && !data)return 2;if(n)memcpy(data,old,n*sizeof *data);int *before=data;size_t original=n;bool ok=append_value(&data,&n,value);if(ok){if(n!=original+1 || (original && memcmp(data,old,original*sizeof *data)!=0)){free(data);return 3;}printf("%zu:%d\n",n,data[n-1]);}else{if(data!=before || n!=original || (n && memcmp(data,old,n*sizeof *data)!=0)){free(data);return 3;}printf("full:%zu\n",n);}free(data);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 Swift Developers

Practice on your own: Online C compiler