This lesson's interactive features are locked, please to keep using them
The malloc function (memory allocation) is a standard library function in C that allocates a specified number of bytes of memory on the heap and returns a pointer to the allocated memory.
This new memory is uninitialized, which means:
free to avoid memory leaks.If you want to make sure that the memory is properly initialized, you can use the calloc function, which allocates the specified number of bytes of memory on the heap and returns a pointer to the allocated memory. This memory is initialized to zero (meaning it contains all zeroes).
void* malloc(size_t size);
size: The number of bytes to allocate.NULL if the allocation fails.// Allocates memory for an array of 4 integers
int *ptr = malloc(4 * sizeof(int));
if (ptr == NULL) {
// Handle memory allocation failure
printf("Memory allocation failed\n");
exit(1);
}
// use the memory here
// ...
free(ptr);
This idea of manually calling malloc and free is what puts the "manual" in "manually managing memory":
free(ptr) to avoid memory leaks.Manually managing memory can be error-prone and tedious, but languages that automatically manage memory (like Python, Java, and C#) have their own trade-offs, usually in terms of performance.
We're working on some of the dynamic memory management tooling that we'll eventually need to build a garbage collector for Sneklang.
Complete the allocate_scalar_array function. It should:
Assume that the calling code will eventually call free on the returned pointer.