realloc ()



	#include <stdio.h>
	#include <stdlib.h>

	/*
	 *  realloc() takes two arguments: address to modify, # of bytes needed
	 *  # of bytes will equal: (new # of elements) * (sizeof(data type))
	 *
	 *  NOTE: realloc() will return a pointer to resized block of memory
	 *  (May be different from previous address)
	 *  Elements from initial block of memory will be preserved in the newly
	 *  resized array up to the intial # of elements
	 *  - All newly allocated elements will contain garbage
	 *  - Downsizing the array can result in lost data
	 *
	 *  ADDITIONAL NOTE: If succesful - and new block of memory was required -
	 *  previous array is freed from memory
	 *  Otherwise realloc() returns NULL
	 */

	int main(void) {

		// Take this int * arr of initial size 10
		// Each element initialized to 0 during calloc()
		int initialSize = 10;
		int *arr = (int *)calloc(initialSize, sizeof(int));

		// realloc can double the size of the previous array
		// IMPORTANT NOTE: If realloc() fails, it returns NULL
		// arr = realloc(arr, (initialSize * 2) * sizeof(int)); ---> DANGEROUS
		// If realloc() returns NULL, the original array still exists
		// but pointer to the array is set to NULL (A.k.A. Memory Leak)
		// and all access to the data is lost
		// INSTEAD use a temporary pointer:
		int *temp = realloc(arr, (initialSize * 2) * sizeof(int));

		// Now temp either points to newly resized array (twice its previous size)
		// OR it points to NULL
		// So check:
		if (temp) // Also can be written as if(temp != NULL)
			arr = temp;
		else
			printf("Failed to reallocate memory\n");

		// If realloc() failed arr still points to original array
		// and temp points to NULL

		// If realloc() succeeds - and new block of memory was required to resize -
		// previous block of memory will be freed automatically

		/////////////////////////////////////////////////////////////////////////////
		free(arr);

		printf("I hope this has helped to teach you how realloc() works :)\n");

		return 0;
	}
						
						

Academic Notice: The code shown here is provided solely as a learning reference. Copying and pasting is intentionally disabled to encourage independent practice. Students should implement solutions on their own to demonstrate understanding. This material is not intended for direct submission in assignments.

Additionally: This code was written by a former CS1 student and may not reflect your professor’s intended solution or instructional approach. For coursework, students are expected to follow examples, conventions, and requirements presented in class and in professor-assigned materials.