Module - 4
Module - 4
Module - 4
Structure
• A structure in C is a user-defined data type
• It combine data items of different kinds
• A structure is a collection of variables (can be of different data types)
under a single name.
• Key features of structure
– Flexibility: Structures allows to store different types of data together.
– Organization: organizes complex data in a more readable and maintainable way.
– Memory Management: Structures can be used to manage memory more
efficiently
– Syntax
struct structureName
{
dataType member1;
dataType member2;
... };
Syntax
• The memory allocated using static allocation remains fixed throughout the
program’s execution and is determined at compile time
Key Features:
1. Allocation and deallocation are done by the compiler.
2. It uses a data structures stack for static memory allocation.
3. Variables get allocated permanently.
4. No reusability.
5. Execution is faster than dynamic memory allocation.
6. Memory is allocated before runtime.
Ex: int a,b[100]; char n[50]; struct stud s;
Dynamic memory allocation
• Dynamic memory allocation refers to allocating and deallocating
memory for variables during the runtime of a program
• dynamic memory allocation allows to request memory from the
operating system as needed and release it when it’s no longer
required
• Provides flexibility in managing memory resources
• In c following functions are used to allocate memory
dynamically
1. malloc()
2. calloc()
3. realloc()
4. free()
malloc
• malloc function in C is used to allocate a block of
memory dynamically
• The memory allocated by malloc() is
uninitialized
• Syntax
– void* malloc(size_t size);
– size: The number of bytes to allocate.
– Returns: A pointer to the allocated memory, or NULL if the
allocation fails
– Ex
int *p;
p = (int *) malloc( 10 * sizeof(int));
The above statement allocates 40 bytes of memory and p is pointing to
the 1st address
malloc
calloc
• Calloc function allocates memory and
initializes all bits to zero
• Syntax :
– int *p;
– p=(int *) calloc(100,sizeof(int))
– A 200 bytes of memory is allocated and 1st address
is hold by the pointer p and all bits are initialized
to 0
– Returns null if sufficient memory is not available
realloc
• It is used to resize a previously
allocated memory block
• It allows to change the size of an
existing memory allocation without
needing to free the old memory
• Syntax
– ptr = realloc(ptr,size)
– ptr will reallocate the existing size with
the new size
realloc
free
• The free() function is used to release
dynamically allocated memory back to the
operating system
• After freeing a memory block, the pointer
becomes invalid, and it is no longer pointing to
a valid memory location
• Syntax
– free(ptr)
Singly linked list