Menu
CoddyTech

Growing Without Losing Data

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

Python list.append handles resizing internally. C realloc may move storage; on failure it returns NULL while the original allocation remains valid. Store the result in a temporary pointer before replacing the owning pointer. Existing aliases may become invalid after successful growth.

Python

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

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) {
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;
}

Porting rule

Keep the original owning pointer until realloc succeeds.

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 Python Developers

Practice on your own: Online C compiler