Allocation and Initialization
Lesson 32 of 48 in Coddy's C for Lua Developers course.
A Lua table constructor creates a managed object, and any index you never assigned reads as nil. C malloc returns raw uninitialized storage or NULL; an element read before it is written holds an indeterminate value, not nil. Check multiplication bounds before computing the allocation size. Lua's garbage collector reclaims tables, but the caller of a C function needs an explicit rule for who frees the returned allocation.
Lua
local values={}
for i=1,3 do values[i]=7 end
print(values[1]+values[2]+values[3])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 *p=malloc(3*sizeof *p);if(!p)return 1;for(size_t i=0;i<3;i++)p[i]=7;printf("%d\n",p[0]+p[1]+p[2]);free(p);
return 0;
}
Porting rule
Check allocation failure and initialize newly allocated storage.
Challenge
EasyInput is count from 0 through 16 and an integer value. make_repeat allocates and initializes count ints to value. Return NULL for count zero or allocation failure. Ownership transfers to the caller, which frees the result. Driver prints their sum, zero for count zero.
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){size_t n;int value;if(scanf("%zu%d",&n,&value)!=2 || n>16)return 1;int *values=make_repeat(n,value);if(n && !values)return 2;int sum=0;for(size_t i=0;i<n;i++)sum+=values[i];free(values);printf("%d\n",sum);return 0;}
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in C for Lua Developers
1Compile and Compute
Run C Across FilesPrinting and CommentsTypes and InitializationInteger Division and RangeFloating ArithmeticRecap: Receipt Total4Functions and Interfaces
Function Arguments Are ValuesHeaders and LinkageMultiple Results via PointersConst Views and MutationRecap: Price Breakdown7Owned Dynamic Memory
Allocation and InitializationOwned Copies and freeGrowing Without Losing DataA Small Vector InterfaceRecap: Owned Integer Buffer2Decisions and Loops
Booleans and BranchesLogical OperatorsSwitch and Enumerated CasesLoop Bounds and ProgressRecap: Admission RulesPractice on your own: Online C compiler