Write a function that allocates memory using malloc.
- Prototype:
void *malloc_checked(unsigned int b); - Returns a pointer to the allocated memory
- if
mallocfails, themalloc_checkedfunction should cause normal process termination with a status value of98
Write a function that concatenates two strings.
- Prototype:
char *string_nconcat(char *s1, char *s2, unsigned int n); - The returned pointer shall point to a newly allocated space in memory, which contains
s1, followed by the firstnbytes ofs2, and null terminated - If the function fails, it should return
NULL - If
nis greater or equal to the length ofs2then use the entire strings2 - if
NULLis passed, treat it as an empty string
Write a function that allocates memory for an array, using malloc.
- Prototype:
void *_calloc(unsigned int nmemb, unsigned int size); - The
_callocfunction allocates memory for an array ofnmembelements ofsizebytes each and returns a pointer to the allocated memory. - The memory is set to zero
- If
nmemborsizeis0, then_callocreturnsNULL - If
mallocfails, then_callocreturnsNULL
FYI: The standard library provides a different function: calloc. Run man calloc to learn more.
Write a function that creates an array of integers.
- Prototype:
int *array_range(int min, int max); - The array created should contain all the values from
min(included) tomax(included), ordered frommintomax - Return: the pointer to the newly created array
- If
min>max, returnNULL - If
mallocfails, returnNULL
Write a function that reallocates a memory block using malloc and free
- Prototype:
void *_realloc(void *ptr, unsigned int old_size, unsigned int new_size); - where
ptris a pointer to the memory previously allocated with a call tomalloc:malloc(old_size) old_sizeis the size, in bytes, of the allocated space forptr- and
new_sizeis the new size, in bytes of the new memory block - The contents will be copied to the newly allocated space, in the range from the start of
ptrup to the minimum of the old and new sizes - If
new_size>old_size, the “added” memory should not be initialized - If
new_size==old_sizedo not do anything and returnptr - If
ptrisNULL, then the call is equivalent tomalloc(new_size), for all values ofold_sizeandnew_size - If
new_sizeis equal to zero, andptris notNULL, then the call is equivalent tofree(ptr). ReturnNULL - Don’t forget to free
ptrwhen it makes sense
FYI: The standard library provides a different function: realloc. Run man realloc to learn more.
Write a program that multiplies two positive numbers.
- Usage:
mul num1 num2 num1andnum2will be passed in base 10- Print the result, followed by a new line
- If the number of arguments is incorrect, print
Error, followed by a new line, and exit with a status of98 num1andnum2should only be composed of digits. If not, printError, followed by a new line, and exit with a status of98- You are allowed to use more than 5 functions in your file
You can use bc (man bc) to check your results.