PLDS UNIT 2 (1)
PLDS UNIT 2 (1)
Answer:
Purpose: The free() function in C is used to deallocate memory that was previously allocated by
malloc(), calloc(), or realloc(). When you allocate memory dynamically, the memory
remains allocated until you explicitly release it using free(). The memory released by free() is
returned to the system and can be used for other purposes.
Significance: Using free() is crucial for managing memory effectively. If you do not use free(),
the allocated memory remains occupied even if it is no longer needed, leading to memory leaks.
Memory leaks can cause a program to consume more memory over time, which can degrade
performance and potentially exhaust system memory, causing crashes or system instability. By
appropriately freeing memory, you ensure that your program uses memory resources efficiently and
avoids such issues.
Example:
2. Discuss the difference between malloc() and calloc() functions in C. Explain their syntax,
usage, and when one might be preferred over the other for memory allocation.
Answer:
Example:
3. Explain the concept of memory leakage in the context of dynamic memory allocation in C.
Discuss how memory leaks occur, their potential consequences, and strategies to prevent them.
Answer:
Memory Leakage: Memory leakage occurs when dynamically allocated memory is not
deallocated using free(), leading to a situation where the memory cannot be reused or
reclaimed by the system. This means that memory is effectively "lost" and unavailable for
other processes or the program itself.
Causes: Memory leaks happen when:
o A pointer to dynamically allocated memory is overwritten without first freeing the memory.
o The program exits without freeing all allocated memory.
o Complex data structures (like linked lists or trees) are not properly freed, causing nested
allocations to be missed.
Consequences:
o Increased Memory Usage: The program uses more memory than necessary, which can lead
to performance degradation.
o Memory Exhaustion: Over time, the system may run out of memory, leading to program
crashes or system instability.
o Reduced Efficiency: The program may become slower as the operating system struggles to
manage fragmented memory.
Prevention Strategies:
o Always use free() to deallocate memory when it is no longer needed.
o Maintain proper tracking of allocated memory using tools like Valgrind, which can detect
memory leaks.
o Implement robust memory management practices, including setting pointers to NULL after
freeing them to avoid dangling pointers.
o Use smart pointers or custom memory management functions to automate memory
deallocation.
Example:
4. Describe the realloc() function in C dynamic memory allocation. Explain its purpose, syntax,
and how it differs from malloc() and calloc(). Provide a brief example demonstrating the
usage of realloc().
Answer:
Purpose: The realloc() function is used to resize a previously allocated memory block. It can
either increase or decrease the size of the memory block, allowing for dynamic adjustment of
memory needs without losing the existing data.
Syntax: void *realloc(void *ptr, size_t size);
o ptr: Pointer to the memory block previously allocated by malloc(), calloc(), or
realloc().
o size: New size of the memory block in bytes.
Difference:
o malloc() allocates a new block of memory of a specified size.
o calloc() allocates memory for an array of elements and initializes it to zero.
o realloc() adjusts the size of an existing memory block, preserving the data in the original
block (if it needs to be moved to a new location due to size adjustment, it handles the data
copying internally).
5. Discuss the potential risks associated with using dynamic memory allocation in C. Explain
common issues such as buffer overflow, dangling pointers, and memory fragmentation, and
provide strategies to mitigate these risks.
Answer:
Buffer Overflow: Occurs when more data is written to a memory block than it can hold. This
can overwrite adjacent memory and lead to unpredictable behavior, crashes, or security
vulnerabilities.
o Mitigation: Ensure array bounds checking and validate input sizes before writing to memory.
Use functions that limit the amount of data written to buffers.
Dangling Pointers: Pointers that refer to deallocated memory. Accessing or modifying data
through dangling pointers can lead to undefined behavior or crashes.
o Mitigation: Set pointers to NULL after freeing memory. Check if pointers are NULL before
dereferencing them.
Memory Fragmentation: Occurs when free memory is scattered in small blocks, leading to
inefficient memory usage and making it difficult to allocate large contiguous memory blocks.
o Mitigation: Use memory pooling techniques and allocate larger blocks of memory when
possible. Periodically compact memory if the environment supports it.
6. Explain the concept of pointer arithmetic in C dynamic memory allocation. Discuss how
pointer arithmetic can be used to navigate through dynamically allocated memory blocks and
access individual elements of arrays. Provide a brief example demonstrating pointer arithmetic
in the context of dynamic memory allocation.
Answer:
Pointer Arithmetic: Involves performing operations on pointers to navigate through memory blocks.
It allows for accessing array elements and traversing dynamically allocated memory using pointer
increments, decrements, addition, and subtraction.
Usage: Pointer arithmetic can be used to move through an array or a block of memory by adjusting
the pointer's value. For example, incrementing a pointer to an integer array moves the pointer to the
next integer in the array. Pointer arithmetic is particularly useful in scenarios where you need to
access elements in a dynamically allocated array or traverse a block of memory without using array
indexing.
Example:
Question 7: Discuss the concept of function pointers in C. Explain what a function pointer is, how
it is declared, and how it can be used to call functions dynamically at runtime. Provide a brief
example demonstrating the declaration and usage of a function pointer.
Answer:
A function pointer in C is a pointer that points to a function instead of a data variable. Function
pointers allow dynamic function calls, enabling flexible and modular code structures such as callback
functions and dynamic dispatch.
Declaration: A function pointer is declared by specifying the return type and the parameter
list of the function it points to, followed by an asterisk (*) and the name of the pointer, all
enclosed in parentheses. For example:
This declares a pointer func_ptr to a function that returns void and takes two int
parameters.
Usage: Function pointers can be used to store the address of functions and invoke functions
dynamically at runtime. They are particularly useful for implementing callback functions,
which are used extensively in event-driven programming.
Example:
In summary, function pointers point to functions and are used for dynamic function calls, whereas
regular pointers point to data variables and are used for data manipulation.
Question 9: Explain the significance of typedefs when working with function pointers in C.
Describe how typedefs can be used to simplify the syntax of function pointer declarations and
enhance code readability. Provide an example demonstrating the usage of typedefs with function
pointers.
Answer:
Significance of Typedefs with Function Pointers: Typedefs simplify the syntax and enhance the
readability of function pointer declarations. Function pointer syntax can be complex and difficult to
understand at first glance. Using typedefs allows you to create a more intuitive name for the function
pointer type, making the code easier to read and maintain.
Usage of Typedefs with Function Pointers: By using typedefs, you can declare a function pointer
type once and then use this new type name to declare function pointers without repeating the entire
function pointer syntax each time.
Example:
Question 11: Describe the concept of callback functions in C using function pointers. Explain how
callback functions allow for flexible and modular program design by enabling functions to be
passed as arguments to other functions. Provide a brief example demonstrating the use of
callback functions with function pointers.
Answer:
Concept of Callback Functions: Callback functions are functions that are passed as arguments to
other functions. They are called, or "called back," at a later point in time as part of a larger operation.
This allows for flexible and modular program design, enabling functions to be reused and composed
in different ways.
Example:
Question 12: Explain the concept of an array of function pointers in C. Describe how an array of
function pointers is declared, initialized, and used to store addresses of functions. Provide a
brief example demonstrating the creation and usage of an array of function pointers.
Answer:
Example:
Question 13: Discuss the role of function pointers in implementing polymorphism in C. Explain
how function pointers enable dynamic method binding and runtime method invocation,
facilitating polymorphic behavior in C programs. Provide an example demonstrating
polymorphism using function pointers.
Answer:
Example:
Question 14: Describe the process of passing function pointers as arguments to other functions
in C. Explain how function pointers can be used to implement higher-order functions and
callbacks, enhancing code modularity and flexibility. Provide an example demonstrating the
passing of function pointers as arguments.
Answer:
Process of Passing Function Pointers as Arguments: Function pointers can be passed as arguments
to other functions, allowing those functions to call the pointed-to function as part of their execution.
This enables the implementation of higher-order functions and callbacks, enhancing code modularity
and flexibility.
Example:
Question 15: Explain the concept of a function pointer to a function returning a pointer in C.
Describe how such function pointers are declared and used, and discuss scenarios where they
can be beneficial in programming. Provide an example illustrating the usage of a function
pointer to a function returning a pointer.
Answer:
Declaration: The declaration involves specifying the return type (pointer type), the function pointer
name, and the parameter list. For example:
This declares a pointer func_ptr to a function that returns an int* and takes two int parameters.
Usage Example:
Question 16: Discuss potential pitfalls and best practices when working with function pointers in
C programming.
Potential Pitfalls:
Concept:
Passing pointers as function arguments allows functions to access and modify data outside their local
scope.
Benefits:
1. Memory Efficiency:
o Passing pointers avoids copying large data structures, reducing memory usage.
2. Direct Data Manipulation:
o Functions can directly modify the original data.
3. Flexibility with Dynamic Data Structures:
o Enables the use of dynamic data structures like linked lists and trees.
Example:
Question 18: Describe the difference between passing by value and passing by reference in
function arguments.
Passing by Value:
Example:
Output: 10
Example:
Output: 20
The original num is modified because modifyReference works with a pointer to num.
Explanation:
Passing by value is safer but less efficient for large data structures.
Passing by reference allows direct modification of the original data and is more efficient for
large structures.
CAT II
UNIT II 2 nd half
data_type member1;
data_type member2;
};
Example:
struct student {
int rollno;
char name[50];
float marks;
};
2
Declare the C structures for the following scenario:
(i) College contains the following fields: College code
(2characters), College Name, year of establishment, number of
courses.
struct College {
char code[3];
char name[100];
int year_established;
int num_courses;
};
struct Course {
char name[100];
int duration;
int num_students;
};
int main() {
// Initializing structure during declaration
struct student s1 = {101, "John", 85.5};
// Accessing structure members
printf("Student Roll No: %d\n", s1.rollno);
printf("Student Name: %s\n", s1.name);
printf("Student Marks: %.2f\n", s1.marks);
return 0;
}
int main() {
// Structure declaration
struct student s2;
return 0;
}
4. How to access the data for structure variables using member operator(‘.’)?
In C, you can access the data for structure variables using the
member operator, which is represented by a dot (.). This operator
allows you to access individual members of a structure variable.
structure_variable.member_name
7. Assume that objects of the type int and float occupy 4 bytes and 4 bytes
respectively. Find the memory requirement for structure variable s?
struct node {
int i;
float j;
};
struct node s[10];
ANSWER:
Each struct node object will occupy 4 bytes (for int) + 4 bytes (for
float) = 8 bytes. So, the memory requirement for s would be 8 bytes
* 10 = 80 bytes.
8. What is self-referential structure?
EXAMPLE:
struct Node {
int data;
struct Node *next; // Pointer to the next Node
};
OUTPUT:
0,2
EXAMPLE:
struct Node {
int data;
struct Node *next; // Pointer to the next Node
};
You can simplify the use of structures by defining typedefs for them, which
allows you to create aliases for structure types, making the code more
readable and easier to maintain.
typedef struct {
int rollno;
char gender;
} Student;
14. State the difference between the dot and -> operators.
The dot (.) operator is used to access members of a structure when working
with the structure itself.
The arrow (->) operator is used to access members of a structure when
working with pointers to that structure.
You can access structure members either by using the dot (.) operator when
working with the structure itself or by using the arrow (->) operator when
working with pointers to the structure.
Example:
struct Point {
int x;
int y;
};
struct Point p;
p.x = 10;
p.y = 20;
ptr->x = 30;
ptr->y = 40;
Predict the output of the given function.
16.
OUTPUT:
DCBA
OUTPUT:
-5
18. Define a structure type book,that would contain book name, author, pages
and price. Write a program to read this data using member operator (‘.’) and display
the same.
19.
How to pass a structure member as an argument of a function? Write a program to
explain it.
examples.
1. Purpose : This is useful when you want to group related data together, such as
multiple marks for a student, or multiple coordinates for a point.
2. Purpose : This is useful when you want to store multiple entities of the same
type, such as multiple students, employees, or songs.
25. Write a calculator program that allows the user to perform basic
song details such as song ID, title, artist and whether its marked as favourite or
not. Design a menu based application that enables the user to: