Menu
CoddyTech

Growing Without Losing Data

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

Java ArrayList hides backing-array growth and keeps the list object stable. C realloc can move storage and invalidate aliases; a temporary result preserves the original allocation when growth fails.

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

Java example


public class Main {

public static void main(String[] args) {
java.util.List<Integer> xs=new java.util.ArrayList<>();xs.add(2);xs.add(4);xs.add(6);System.out.println(xs.get(2));
}
}

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

Practice on your own: Online C compiler