0% found this document useful (0 votes)
14 views

PLDS UNIT 2 (1)

Uploaded by

menahamenu04
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
14 views

PLDS UNIT 2 (1)

Uploaded by

menahamenu04
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 51

CAT-1

UNIT 2 1ST HALF


1. Explain the significance of the free() function in C dynamic memory allocation. Describe its
purpose and why it is important to use it appropriately when working with dynamically
allocated memory.

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:

 malloc() Syntax: void *malloc(size_t size);


o Usage: Allocates a block of memory of the specified size in bytes. The content of the
allocated memory is uninitialized, meaning it contains garbage values.
o When to Use: Use malloc() when you need a single block of memory and initialization of
the memory is not a concern or you plan to initialize it manually later.
 calloc() Syntax: void *calloc(size_t num, size_t size);
o Usage: Allocates memory for an array of num elements, each of size size bytes. The
allocated memory is initialized to zero.
o When to Use: Use calloc() when you need to allocate memory for an array and want to
ensure that all elements are initialized to zero, which can help prevent potential issues with
uninitialized memory.

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:

void (*func_ptr)(int, int);

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:

Concept of an Array of Function Pointers: An array of function pointers is a collection of pointers,


each pointing to a function. This allows for storing and accessing multiple functions using array
indexing, providing a convenient way to manage a set of related functions.

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:

Role of Function Pointers in Implementing Polymorphism: Function pointers enable


polymorphism in C by allowing functions to be dynamically selected and invoked at runtime. This
facilitates dynamic method binding and runtime method invocation, which are key aspects of
polymorphic behavior.

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:

Concept of Function Pointer to a Function Returning a Pointer: A function pointer to a function


returning a pointer is a pointer that points to a function which, when called, returns a pointer to some
data type.

Declaration: The declaration involves specifying the return type (pointer type), the function pointer
name, and the parameter list. For example:

int* (*func_ptr)(int, int);

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:

1. Improper Type Casting:


o Mistake: Casting function pointers to incorrect types.
o Example: Casting a void (*func)() to int (*func)(int).
o Avoidance: Always use the correct type for function pointers.
2. Null Pointer Dereferencing:
o Mistake: Dereferencing a function pointer that is NULL.
o Example: void (*func)() = NULL; func(); results in undefined behavior.
o Avoidance: Always check if the function pointer is not NULL before calling it.
3. Memory Management Issues:
o Mistake: Using function pointers to access memory that has been freed.
o Example: Assigning a function pointer to a function located in freed dynamic memory.
o Avoidance: Ensure the memory containing the function is valid for the lifetime of the
pointer.
Best Practices:

1. Initialize Function Pointers:


o Always initialize function pointers, even if it's to NULL.
2. Type Safety:
o Ensure function pointers are correctly typed to avoid type mismatches.
3. Check for NULL:
o Before invoking a function pointer, always check if it's NULL to prevent dereferencing null
pointers.
4. Documentation:
o Document the function pointer's expected function signature and behavior clearly.

Question 17: Explain the concept of passing pointers as function arguments in C.

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:

 The function receives a copy of the argument's value.


 Modifications to the parameter do not affect the original argument.

Example:

Output: 10

 The original num remains unchanged because modifyValue receives a copy.


Passing by Reference:

 The function receives a reference (pointer) to the argument.


 Modifications to the parameter affect the original argument.

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

1 Define a structure? Write the syntax for structure declaration with


an example.

A structure in C is a user-defined data type that allows grouping


together variables of different data types under one name.

Syntax for structure declaration:


struct structure_name {

data_type member1;

data_type member2;

// more members if needed

};

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;
};

(ii) Each course is associated with course name (String), duration,


number of students.(A College can offer 1 to 50 such courses)

struct Course {
char name[100];
int duration;
int num_students;
};

3.How to initialize structures in “C”?


In C, you can initialize a structure either during its declaration or after its
declaration. When you initialize a structure during its declaration, you use
braces {}
EXAMPLE:
// Structure declaration
struct student {
int rollno;
char name[50];
float marks;
};

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;

// Initializing structure after declaration


s2.rollno = 102;
sprintf(s2.name, "Alice"); // Using sprintf to copy string into char array
s2.marks = 90.0;

// Accessing structure members


printf("Student Roll No: %d\n", s2.rollno);
printf("Student Name: %s\n", s2.name);
printf("Student Marks: %.2f\n", s2.marks);

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.

You can represent it by the structure variable and dot followed by


member name

Here's the syntax:

structure_variable.member_name

5.Find the number of bytes taken by the below structure in memory.


5.#include<stdio.h
> struct stu {
int rollno;
char gender;
};
Output
Size of struct stu in memory depends on the size of its members and padding
for alignment. Assuming an integer takes 4 bytes and a char takes 1 byte, the
size of this structure would be 8 bytes.
Or
5

6.Write the correct syntax to access the member of ith structure in


the array of structures.
struct emp {
int age;
} s[10];
ANSWER:
S[i].age;(or)
s[i].age = 30;

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?

A self-referential structure is a structure that contains a pointer member that


points to a variable of the same structure type. It's commonly used in linked
list implementations.

EXAMPLE:
struct Node {
int data;
struct Node *next; // Pointer to the next Node
};

9. Predict the output of the code: (GATE)


#include<stdio.h>
struct ournode {
char x, y, z;
};
int main() {
struct ournode p = {'1', '0', 'a+2’};
struct ournode *q = &p;
printf("%c,%c", *((char*)q+1), *((char*)q+2));
return 0;
}
OUTPUT:
ERROR OR 0,C OR 0, +

10. Predict the output of the code: (GATE)

OUTPUT:
0,2

11. Define self-referential Structure.


A self-referential structure is a structure that contains a pointer member that
points to a variable of the same structure type. It's commonly used in linked
list implementations.

EXAMPLE:
struct Node {
int data;
struct Node *next; // Pointer to the next Node
};

12. How will you simplify the use of Structures?

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;

13. Write a simple C program for implementing pointers to structures.

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.

15.How will you access the structure members?

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;

struct Point *ptr = &p;

ptr->x = 30;

ptr->y = 40;
Predict the output of the given function.
16.
OUTPUT:
DCBA

17. Predict the output of the code:

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.

To pass a structure member as an argument of a function in C, you simply need to


specify the member type as the parameter type in the function definition. Here's an
example:
20. Write a program to pass entire structure as an argument of a structure.

To pass an entire structure as an argument to a function, you simply declare


the function parameter as the structure type. Here's an example:
21. Write a C program to calculate student-wise total marks for three
students using array of structure.
OUTPUT:
22. Write a C program using array of structure to create employee records with the
following fields: emp-id, name, designation, address, salary and display it.
OUTPUT:

23. Write a C program using nested structures to read 3 employees details


with the following fields; emp-id, name, designation, address, da ,hra
andcalculate gross salary of each employee.
OUTPUT:
24. Distinguish between Arrays within Structures and Array of Structure with

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

arithmetic operations (+,-,*,%). Implement a function pointer based

approach to select and execute the desired operations.


26.Develop a program to manage a music library. Design a structure to hold

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:

i) Display song information.

ii) Add a new song to the library

iii) Display all songs by a specific artist

iv) Display the total number of songs in the library

v) Mark/unmark a song as a favourite.


27.A student result publishing system has to get the details of the students and
the print the result in rank order. Define a structure called STUDENT with data
members Name, Roll No, three subject marks, total, average and rank.Perform
the following operations by passing structure to a function by value.

vi) Get the student details for ‘N’ students

vii) Find the total, average of the students

viii) Find the rank of the students

ix) Display the details of the students in rank order.

You might also like