0% found this document useful (0 votes)
3 views38 pages

String Manip

Uploaded by

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

String Manip

Uploaded by

kgautam21080410
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

1.

Importance of '\0' (Null Character)

 In C, a string is a character array ending with '\0' (null


terminator).

 Example:

char str[] = "hello"; // actually stored as: h e l l o \0

 If '\0' is missing, functions from <string.h> will:


Keep reading memory → undefined behavior (garbage output /
crash)

🔹 2. strlen(a)

 Finds length of string (excluding '\0')

 Example:

strlen("hello") = 5

 Counts only characters, NOT the null character.

🔹 3. strcpy(a, b)

 Copies string b into a

 Example:

char a[10];
strcpy(a, "hi");

 Now a = "hi"

4. strcat(a, b)

 Concatenates (joins) string b to end of a

 Example:

char a[20] = "hello";


strcat(a, " world");

 Result: "hello world"

5. strchr(a, ch)

 Finds first occurrence of character ch in string a

 Returns:

o Address (pointer) if found

o NULL if not found

Example:

strchr("hello", 'l') → points to first 'l'

6. strcmp(a, b)

 Compares two strings lexicographically (dictionary order)


Returns:

 0 → if both strings are equal

 >0 (or 1) → if a > b

 <0 (or -1) → if a < b

Example:

strcmp("apple", "banana") → negative value


strcmp("cat", "cat") → 0

C program demonstrating ALL string


functions
#include <stdio.h>

#include <string.h>

int main() {

char a[50] = "Hello";

char b[50] = "World";

char c[50];

// 1. strlen()

printf("Length of a = %d\n", strlen(a));

// 2. strcpy()

strcpy(c, a);

printf("After strcpy, c = %s\n", c);

// 3. strcat()

strcat(a, b);

printf("After strcat, a = %s\n", a);

// 4. strchr()

char *ptr = strchr(a, 'o');

if (ptr != NULL)

printf("First occurrence of 'o' in a = %c\n", *ptr);

else

printf("Character not found\n");

// 5. strcmp()

int result = strcmp(a, b);


if (result == 0)

printf("Strings are equal\n");

else if (result > 0)

printf("a is greater than b\n");

else

printf("a is less than b\n");

return 0;

Logic (Simple Understanding)

 strlen(a) → counts characters in "Hello" → 5

 strcpy(c, a) → copies "Hello" into c

 strcat(a, b) → joins "Hello" + "World" → "HelloWorld"

 strchr(a, 'o') → finds first 'o' in "HelloWorld"

 strcmp(a, b) → compares "HelloWorld" and "World"

 Output
Length of a = 5
After strcpy, c = Hello
After strcat, a = HelloWorld
First occurrence of 'o' in a = o
a is greater than b

User-Defined String Functions

Instead of using <string.h>, you write your own logic using:

 Iteration (loops)

 Pointer arithmetic

 Recursion

1. my_strlen() – Find length

Iterative

int my_strlen(char *str) {


int count = 0;
while (str[count] != '\0') {
count++;
}
return count;
}
Pointer version

int my_strlen_ptr(char *str) {


char *start = str;
while (*str != '\0') {
str++;
}
return str - start;
}

2. my_strcpy() – Copy string

void my_strcpy(char *dest, char *src) {


while (*src != '\0') {
*dest = *src;
dest++;
src++;
}
*dest = '\0';
}

3. my_strcmp() – Compare strings

int my_strcmp(char *a, char *b) {


while (*a && *b) {
if (*a != *b)
return *a - *b;
a++;
b++;
}
return *a - *b;
}

4. my_strchr() – Find character

char* my_strchr(char *str, char ch) {


while (*str != '\0') {
if (*str == ch)
return str;
str++;
}
return NULL;
}

5. my_strcat() – Concatenate strings

void my_strcat(char *dest, char *src) {


while (*dest != '\0') {
dest++;
}
while (*src != '\0') {
*dest = *src;
dest++;
src++;
}
*dest = '\0';
}

Pointer arithmetic:

 *str → value

 str++ → next character

No built-in functions used

Recursion reduces problem size

SUMMARY

my_strlen → counts characters

my_strcpy → copies source to destination

my_strcmp → compares ASCII values

my_strchr → returns pointer to character

my_strcat → appends strings

C program with all user-defined string functions

#include <stdio.h>

// 1. my_strlen

int my_strlen(char *str) {

int count = 0;

while (str[count] != '\0')

count++;

return count;

// 2. my_strcpy

void my_strcpy(char *dest, char *src) {

while (*src != '\0') {


*dest = *src;

dest++;

src++;

*dest = '\0';

// 3. my_strcmp

int my_strcmp(char *a, char *b) {

while (*a && *b) {

if (*a != *b)

return *a - *b;

a++;

b++;

return *a - *b;

// 4. my_strchr

char* my_strchr(char *str, char ch) {

while (*str != '\0') {

if (*str == ch)

return str;

str++;

return NULL;

// 5. my_strcat

void my_strcat(char *dest, char *src) {

while (*dest != '\0')

dest++;

while (*src != '\0') {


*dest = *src;

dest++;

src++;

*dest = '\0';

int main() {

char a[50] = "Hello";

char b[50] = "World";

char c[50];

char *ptr;

// strlen

printf("Length of a = %d\n", my_strlen(a));

// strcpy

my_strcpy(c, a);

printf("After copying, c = %s\n", c);

// strcat

my_strcat(a, b);

printf("After concatenation, a = %s\n", a);

// strchr

ptr = my_strchr(a, 'o');

if (ptr != NULL)

printf("First 'o' found at: %c\n", *ptr);

else

printf("Character not found\n");

// strcmp

int res = my_strcmp(a, b);

if (res == 0)
printf("Strings are equal\n");

else if (res > 0)

printf("a is greater than b\n");

else

printf("a is less than b\n");

return 0;

OUTPUT

Length of a = 5

After copying, c = Hello

After concatenation, a = HelloWorld

First 'o' found at: o

a is greater than b

ERROR DEMO

1. char *name[10] vs char name[10]

Wrong understanding

char *name[10];

 This is array of 10 pointers, each pointing to a char

 NOT a single string

Correct for string

char name[10];

 This is a character array (string)

Key Difference

 char *name[10] → 10 strings (or pointers)

 char name[10] → 1 string (max 9 chars + '\0')

2. Assignment using =

Wrong

char name[10];
name = "choco"; // ERROR

Arrays cannot be assigned after declaration

Correct ways
char name[10] = "choco"; // initialization

3. printf("%s\n", *name);

Wrong

printf("%s\n", *name);

 *name → gives first character, not string

 %s expects address of string

Correct

printf("%s\n", name);

4. Error without '\0' (VERY IMPORTANT )

Problem Code

#include <stdio.h>
#include <string.h>

int main() {
char str[5] = {'H','e','l','l','o'}; // NO '\0'

printf("Length = %d\n", strlen(str)); // undefined


printf("String = %s\n", str); // garbage output

return 0;
}

What happens?

 No null terminator → functions don’t know where to stop

 strlen() keeps counting beyond array

 printf() prints garbage values

Correct Version

char str[6] = {'H','e','l','l','o','\0'};

OR simply:

char str[] = "Hello";

Final Summary

 Strings must end with '\0'

 char *name[10] ≠ char name[10]


 Arrays cannot be assigned using =

 %s needs base address, not *name

 Missing '\0' → undefined behavior

Command Line Arguments

Command line arguments allow us to provide input data to a


program at the time of execution.

Example

[Link] 18 27

 [Link] → executable file (program)

 18 and 27 → arguments passed to the program (inputs)

Key Points

 All command line arguments are received as strings inside


the program.

 Even if numbers are passed, they are treated as string data


types.

 To use numeric values, we must convert strings to integers.

Use the atoi() function (in C/C++) to convert a string to an


integer.

Example:

int num = atoi(argv[1]);

Summary

 Input is given during execution.

 Arguments are passed via command line.

 Stored as strings → must be converted when needed.


Usage of Argument Count (argc) and Argument Vector (argv)

Definition of main() with Arguments

To use command line arguments, the main() function is defined


as:

int main(int argc, char *argv[]) {


// code
}

argc (Argument Count)

 argc is an integer variable.

 It stores the total number of arguments passed in the


command line.

 It includes the executable name as the first argument.

 The value of argc is always non-negative.

Example

[Link] 18 27

 argc = 3

o argv[0] → "[Link]"

o argv[1] → "18"

o argv[2] → "27"

argv (Argument Vector)

 argv is an array of character pointers (char *argv[]).

 It stores all command line arguments as strings.

 Each element points to one argument.

Accessing Arguments

 argv[0] → Name of the executable

 argv[1] → First argument

 argv[2] → Second argument

 and so on...

Important Notes

 All arguments are stored as strings, even if they are


numbers.
 Use functions like atoi() to convert string arguments into
integers.

 argv[argc] is always NULL.

#include <stdio.h>

#include <stdlib.h>

int main(int argc, char *argv[]) {

printf("Number of arguments: %d\n", argc);

for(int i = 0; i < argc; i++) {

printf("argv[%d] = %s\n", i, argv[i]);

return 0;

Program: Sum of Command Line Arguments

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

int main(int argc, char *argv[]) {


int sum = 0;

// Start from 1 because argv[0] is program name

for(int i = 1; i < argc; i++) {


sum += atoi(argv[i]); // convert string to integer
}

printf("Sum = %d\n", sum);

return 0;
}

argc → number of arguments

argv[i] → each argument (as string)

atoi() → converts string → integer

Loop runs from i = 1 (ignores program name)

If no arguments are given:

a
Output will be:

Sum = 0

C Program with Error Handling (Non-numeric Inputs)


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

// Function to check if string is a valid number


int isNumber(char str[]) {
int i = 0;
// Handle negative numbers
if (str[0] == '-' || str[0] == '+') {
i = 1;
}

// Check remaining characters


for (; str[i] != '\0'; i++) {
if (!isdigit(str[i])) {
return 0; // Not a number
}
}

return 1; // Valid number


}

int main(int argc, char *argv[]) {


int sum = 0;

if (argc == 1) {
printf("No numbers provided.\n");
return 1;
}

for (int i = 1; i < argc; i++) {


if (isNumber(argv[i])) {
sum += atoi(argv[i]);
} else {
printf("Invalid input: %s is not a number\n", argv[i]);
}
}

printf("Sum = %d\n", sum);

return 0;
}
a 10 20 abc 30

✅ Output

Invalid input: abc is not a number


Sum = 60

DYNAMIC MEMORY ALLOCATION

Memory is allocated at runtime based on actual need.

Helps in:

 Efficient memory usage

 Flexibility in handling data

 Avoiding wastage and overflow issues

Key Functions in C

 malloc() → allocates memory

 calloc() → allocates and initializes memory

 realloc() → resizes allocated memory

 free() → deallocates memory

Memory Allocation

Memory in C programs can be allocated in three ways:

1. Static Allocation

 Memory is decided by the compiler.

 Allocation happens at load time (before execution).

 Size is fixed and cannot be changed.

Examples

int a;
float b;
int arr[20];

Key Points

 Memory is reserved once.


 Exists throughout the entire program execution.

 No flexibility → may lead to wastage or shortage.

2. Automatic Allocation

 Also decided by the compiler.

 Allocation happens at run time.

 Memory is allocated when a block/function is entered and


released when it exits.

 Uses stack memory.

Example

void func() {
int x = 10; // allocated when function is called
} // deallocated when function ends

Key Points

 Temporary storage

 Managed automatically

 Faster access (stack)

 Cannot be resized

3. Dynamic Allocation

 Memory is allocated during program execution (run time).

 Done using library functions.

 Provides flexibility to allocate and deallocate memory as


needed.

 Uses heap memory.

Examples

int *ptr;
ptr = (int*) malloc(5 * sizeof(int));

Allocation Memory Flexibilit Managed


Type
Time Area y By

Data
Static Load time No Compiler
segment

Automati
Run time Stack No Compiler
c

Dynamic Run time Heap Yes Programme


Allocation Memory Flexibilit Managed
Type
Time Area y By

Dynamic Allocation – Memory Region Used

 Dynamic memory allocation uses the Heap region of the


memory segment.

Explanation

 The heap is a portion of memory used for runtime (dynamic)


allocation.

 Memory is allocated using functions like:

o malloc()

o calloc()

o realloc()

 The allocated memory remains in the heap until it is


explicitly freed using free().

Key Points

 Heap memory is not managed automatically (unlike stack).

 Programmer must manually allocate and deallocate memory.

 Helps in handling:

o Variable-sized data

o Data that grows/shrinks during execution

Malloc() – Memory Allocation

Definition
 malloc() is used to dynamically allocate memory during
runtime.

 It allocates the requested number of bytes in the heap


memory.

Key Features

 Returns a void pointer (void*) pointing to the first byte of


allocated memory.

 The returned pointer can be type-casted to any required


data type.

 If allocation fails, it returns NULL.

 Allocated memory is not initialized (contains garbage


values).

Syntax

void *malloc(size_t N);

 N → number of bytes to allocate

Example

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

int main() {
int *ptr;

ptr = (int*) malloc(sizeof(int)); // allocate memory for 1 integer

if (ptr == NULL) {
printf("Memory allocation failed\n");
return 1;
}

*ptr = 10;
printf("Value = %d\n", *ptr);
free(ptr); // release memory
return 0;
}

Memory Representation (Conceptual)

STACK HEAP
----- -----
ptr ───────────────► [5000] (allocated block)
[5001]
[5002]
[5003]

 ptr (in stack) stores the address of heap memory

 Actual data is stored in the heap

Important Points

 Always check:

if(ptr == NULL)

 Always release memory using:

free(ptr);

 Avoid memory leaks by freeing unused memory

Quick Summary

 malloc() → allocates memory

 Returns pointer → needs typecasting

 Not initialized → may contain garbage

 Must use free()

PROGRAMS

1. Allocate Memory for One Integer

#include <stdio.h>
#include <stdlib.h>
int main() {
int *ptr;
ptr = (int*) malloc(sizeof(int));
if (ptr == NULL) {
printf("Memory allocation failed\n");
return 1;
}
*ptr = 25;
printf("Value = %d\n", *ptr);
free(ptr);
return 0;
}

2. Allocate Memory for Array (n elements)


#include <stdio.h>
#include <stdlib.h>
int main() {
int n, *arr;
printf("Enter number of elements: ");
scanf("%d", &n);
arr = (int*) malloc(n * sizeof(int));
if (arr == NULL) {
printf("Memory allocation failed\n");
return 1;
}
printf("Enter elements:\n");
for (int i = 0; i < n; i++) {
scanf("%d", &arr[i]);
}
printf("Elements are:\n");
for (int i = 0; i < n; i++) {
printf("%d ", arr[i]);
}
free(arr);
return 0;
}

3. Sum of Array Elements using malloc

#include <stdio.h>
#include <stdlib.h>
int main() {
int n, *arr, sum = 0;
printf("Enter size: ");
scanf("%d", &n);
arr = (int*) malloc(n * sizeof(int));
if (arr == NULL) {
printf("Memory allocation failed\n");
return 1;
}
for (int i = 0; i < n; i++) {
scanf("%d", &arr[i]);
sum += arr[i];
}

printf("Sum = %d\n", sum);

free(arr);
return 0;
}

4. Find Maximum Element


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

int main() {
int n, *arr, max;

printf("Enter size: ");


scanf("%d", &n);

arr = (int*) malloc(n * sizeof(int));

if (arr == NULL) {
printf("Memory allocation failed\n");
return 1;
}

for (int i = 0; i < n; i++) {


scanf("%d", &arr[i]);
}

max = arr[0];
for (int i = 1; i < n; i++) {
if (arr[i] > max)
max = arr[i];
}

printf("Maximum = %d\n", max);

free(arr);
return 0;
}

CALLOC

calloc () – Contiguous Allocation

Definition

 calloc () is used to allocate memory for multiple elements


(array).

 It allocates contiguous memory blocks.

 All allocated memory is initialized to zero.


Key Features

 Returns a void pointer (void*) to the allocated memory.

 Can be type-casted to any pointer type.

 If allocation fails, it returns NULL.

 Memory is automatically initialized to 0 (unlike malloc ()).

Syntax

void *calloc(size_t nmemb, size_t size);

 nmemb → number of elements

 size → size of each element (in bytes)

Example

int *ptr = (int*) calloc(3, sizeof(int));

Allocates memory for 3 integers, all initialized to 0

Memory Representation (Conceptual)

STACK HEAP
----- -----
ptr ───────────────► [5000] = 0
[5001] = 0
[5002] = 0
[5003]
...

 ptr stores the starting address of allocated memory

 All values are initialized to 0

Simple Coding Example

#include <stdio.h>
#include <stdlib.h>
int main() {
int *arr, n = 3;
arr = (int*) calloc(n, sizeof(int));
if (arr == NULL) {
printf("Memory allocation failed\n");
return 1;
}
printf("Values after calloc:\n");
for (int i = 0; i < n; i++) {
printf("%d ", arr[i]); // all will be 0
}
free(arr);
return 0;
}

Output

Values after calloc:


000

Feature malloc() calloc()

Initialization Garbage values Zero initialized

Arguments 1 2

Use case Single block Array allocation

Programs

1. Basic Program (Check Zero Initialization)

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

int main() {
int *arr, n = 5;
arr = (int*) calloc(n, sizeof(int));
if (arr == NULL) {
printf("Memory allocation failed\n");
return 1;
}
printf("Elements after calloc:\n");
for (int i = 0; i < n; i++) {
printf("%d ", arr[i]); // all zeros
}
free(arr);
return 0;
}

Output
Elements after calloc:
00000

2. Input and Display Array

#include <stdio.h>
#include <stdlib.h>
int main() {
int *arr, n;
printf("Enter number of elements: ");
scanf("%d", &n);
arr = (int*) calloc(n, sizeof(int));
if (arr == NULL) {
printf("Memory allocation failed\n");
return 1;
}
printf("Enter elements:\n");
for (int i = 0; i < n; i++) {
scanf("%d", &arr[i]);
}
printf("Elements are:\n");
for (int i = 0; i < n; i++) {
printf("%d ", arr[i]);
}
free(arr);
return 0;
}

Sample Input/Output

Enter number of elements: 3


Enter elements:
10 20 30
Elements are:
10 20 30

3. Sum of Elements

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

int main() {
int *arr, n, sum = 0;

printf("Enter size: ");


scanf("%d", &n);

arr = (int*) calloc(n, sizeof(int));

if (arr == NULL) {
printf("Memory allocation failed\n");
return 1;
}

printf("Enter elements:\n");
for (int i = 0; i < n; i++) {
scanf("%d", &arr[i]);
sum += arr[i];
}

printf("Sum = %d\n", sum);

free(arr);
return 0;
}

Sample Output

Enter size: 4
Enter elements:
5 10 15 20
Sum = 50

4. Count Even and Odd Numbers

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

int main() {
int *arr, n, even = 0, odd = 0;

printf("Enter size: ");


scanf("%d", &n);

arr = (int*) calloc(n, sizeof(int));

if (arr == NULL) {
printf("Memory allocation failed\n");
return 1;
}

printf("Enter elements:\n");
for (int i = 0; i < n; i++) {
scanf("%d", &arr[i]);

if (arr[i] % 2 == 0)
even++;
else
odd++;
}

printf("Even = %d\nOdd = %d\n", even, odd);


free(arr);
return 0;
}

Sample Output

Enter size: 5
Enter elements:
12345
Even = 2
Odd = 3

REALLOC

Definition

 realloc() is used to modify (increase or decrease) the size of


previously allocated memory.

 It works only on memory allocated using malloc() or calloc().

Key Features

 Returns a pointer to the new memory block.

 The new block may be at the same location or a new


location.

 If allocation fails → returns NULL.

 If it fails, the original memory remains unchanged.

Syntax

void *realloc(void *ptr, size_t size);

 ptr → pointer to previously allocated memory

 size → new size in bytes

Special Cases

 If ptr == NULL → behaves like malloc(size)

 If size == 0 and ptr != NULL → behaves like free(ptr)

 Should be used only with dynamically allocated memory


1. Increase Array Size using realloc()

#include <stdio.h>
#include <stdlib.h>
int main() {
int *arr, n = 3;
arr = (int*) malloc(n * sizeof(int));
if (arr == NULL) {
printf("Memory allocation failed\n");
return 1;
}
// Initial values
for (int i = 0; i < n; i++) {
arr[i] = i + 1;
}
// Increase size to 5
arr = (int*) realloc(arr, 5 * sizeof(int));
if (arr == NULL) {
printf("Reallocation failed\n");
return 1;
}

// Add new values


for (int i = 3; i < 5; i++) {
arr[i] = i + 1;
} printf("Elements:\n");
for (int i = 0; i < 5; i++) {
printf("%d ", arr[i]);
}
free(arr);
return 0;
}

Output

Elements:
12345

2. Take Input, Then Expand Array

#include <stdio.h>
#include <stdlib.h>
int main() {
int *arr, n, new_n;
printf("Enter initial size: ");
scanf("%d", &n);
arr = (int*) malloc(n * sizeof(int));
if (arr == NULL) {
printf("Memory allocation failed\n");
return 1;
}
printf("Enter elements:\n");
for (int i = 0; i < n; i++) {
scanf("%d", &arr[i]);
}
printf("Enter new size: ");
scanf("%d", &new_n);
arr = (int*) realloc(arr, new_n * sizeof(int));
if (arr == NULL) {
printf("Reallocation failed\n");
return 1;
}
// Input extra elements if size increased
if (new_n > n) {
printf("Enter new elements:\n");
for (int i = n; i < new_n; i++) {
scanf("%d", &arr[i]);
}
}

printf("Final array:\n");
for (int i = 0; i < new_n; i++) {
printf("%d ", arr[i]);
}
free(arr);
return 0;
}

Sample Input/Output

Enter initial size: 3


Enter elements:
10 20 30
Enter new size: 5
Enter new elements:
40 50
Final array:
10 20 30 40 50

3. Reduce Array Size

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

int main() {
int *arr, n = 5;

arr = (int*) malloc(n * sizeof(int));

if (arr == NULL) {
printf("Memory allocation failed\n");
return 1;
}

for (int i = 0; i < n; i++) {


arr[i] = (i + 1) * 10;
}

// Reduce size to 3
arr = (int*) realloc(arr, 3 * sizeof(int));

if (arr == NULL) {
printf("Reallocation failed\n");
return 1;
}

printf("After reducing size:\n");


for (int i = 0; i < 3; i++) {
printf("%d ", arr[i]);
}

free(arr);
return 0;
}

Output

After reducing size:


10 20 30

Realloc() Example Explanation

Code

int* ptr = (int*) calloc (3, sizeof(int));


ptr = (int*) realloc(ptr, 4 * sizeof(int));

Step-by-Step Understanding

Step 1: calloc() Allocation

ptr = (int*) calloc(3, sizeof(int));

 Allocates memory for 3 integers

 All values are initialized to 0

Heap (Initial)
Address Value
5000 0
5001 0
5002 0

Step 2: realloc() Expansion

ptr = (int*) realloc(ptr, 4 * sizeof(int));

 Resizes memory to hold 4 integers

 Memory may:

o Extend in same location OR

o Move to a new location

Important Behavior

Existing Data is Preserved

0 0 0 ?

New Memory is NOT Initialized

 The 4th element contains garbage value (X)

Heap After realloc()

Address Value
5000 0
5001 0
5002 0
5003 X ← new memory (uninitialized)
free() – Deallocation of Memory

Definition

 free() is used to release dynamically allocated memory.

 It returns the memory back to the heap, making it available


for reuse.

Syntax

free(ptr);

 ptr → pointer to memory previously allocated using:

o malloc()

o calloc()

o realloc()

Key Points

 No need to specify size while freeing memory.

 The system keeps track of allocated size using bookkeeping


information.

 After free(), the pointer still exists but becomes a dangling


pointer.

Memory Representation

Before free()

STACK HEAP
----- -----
ptr ───────────────► [5000] (allocated block)
[5001]
[5002]

After free(ptr)

STACK HEAP
----- -----
ptr (5000) → Memory returned to heap
(available for reuse)

DMA ERRORS
free(ptr);
*ptr = 10; // Undefined behaviour

INSTEAD

free(ptr);
ptr = NULL; // good practice

A memory leak is a situation in a program where memory is


allocated but never properly released, even when it is no longer
needed.

How it happens

When a program:

1. Requests memory (using functions like malloc, new, etc.)

2. Uses it

3. Forgets to release it (free, delete not called)

That memory stays occupied forever (until program ends).

Example 1: Memory Leak

#include <stdio.h>

#include <stdlib.h>
int main() {

int *ptr = (int*) malloc(sizeof(int));

*ptr = 10;

printf("Value: %d\n", *ptr);

// Forgot to free memory

// free(ptr);

return 0;

Output:

Value: 10

Problem:

 No runtime error, BUT memory is never freed → memory leak

 If repeated many times → program may crash later

Example 2: Memory Leak inside Loop

#include <stdio.h>

#include <stdlib.h>

int main() {

while (1) {

int *ptr = (int*) malloc(sizeof(int));

// No free(ptr);

return 0;

Result:

 Program keeps allocating memory infinitely

 Eventually:

Memory allocation failed / program crash


EXAMPLE

Using Freed Memory (Serious Error)

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

int main() {
int *ptr = (int*) malloc(sizeof(int));

*ptr = 20;
free(ptr); // memory released

printf("%d\n", *ptr); // ERROR: using freed memory

return 0;
}

Possible Output:

 Garbage value OR

 Segmentation fault

Structures in C
A structure (struct) in C is a user-defined data type that allows
you to group different types of variables under one name.

Why use structures?

In normal variables:

 You store one type at a time (int, float, char)

But in real life, one entity has multiple attributes.


Example: A student has:

 Name (string)

 Age (int)

 Marks (float)

Structure helps combine all these into one unit

Syntax

struct structure_name {
data_type variable1;
data_type variable2;
...
};

Declaration of Structure

Defining a structure

struct Student {
char name[50];
int age;
float marks;
};

This only creates a blueprint, not actual variables.

Declaring structure variables

struct Student s1, s2;

Now s1 and s2 are variables of type struct Student.

2. Initialization of Structure

Method 1: After declaration (using dot operator)

Dot
operator

Used to access
members

#include <stdio.h>
#include <string.h>
struct Student {
char name[50];
int age;
float marks;
};
int main() {
struct Student s1;
strcpy([Link], "abc");
[Link] = 20;
[Link] = 90.5;
printf("%s %d %.2f", [Link], [Link], [Link]);
return 0;
}
Method 2: Direct initialization (at declaration)

struct Student s1 = {"Vidhya", 20, 90.5};

Order must match structure members:

 name → age → marks

Method 3: Partial initialization

struct Student s1 = {"Vidhya", 20};

Remaining values:

 marks → automatically set to 0

Method 4: Using designated initialization (modern C)

struct Student s1 = {
.name = "Vidhya",
.age = 20,
.marks = 90.5
};

Order does not matter here ✔

PROGRAM

#include <stdio.h>

#include <string.h>

// Define structure

struct Student {

char name[50];

int age;

float marks;

};

int main() {

struct Student s1; // Declare structure variable

// Assign values

strcpy([Link], "Vidhya");

[Link] = 30;
[Link] = 85.5;

// Print values

printf("Name: %s\n", [Link]);

printf("Age: %d\n", [Link]);

printf("Marks: %.2f\n", [Link]);

return 0;

OUTPUT

Name: Vidhya

Age: 30

Marks: 85.50

struct Student → defines a new data type

s1 → variable of that structure

[Link], [Link] → access members using dot (.) operator

Basic Structure Program (Student Details)

#include <stdio.h>

#include <string.h>

struct Student {

char name[50];

int age;

};

int main() {

struct Student s1;

strcpy([Link], "abc");

[Link] = 20;

printf("Name: %s\n", [Link]);

printf("Age: %d\n", [Link]);

return 0;

}
Structure with Initialization

#include <stdio.h>

struct Student {
char name[50];
int marks;
};
int main() {
struct Student s1 = {"Rahul", 85};

printf("Name: %s\n", [Link]);


printf("Marks: %d\n", [Link]);

return 0;
}

Output

Name: Rahul
Marks: 85

3. Array of Structures

#include <stdio.h>
struct Student {
char name[20];
int marks;
};
int main() {
struct Student s[2] = {
{"Asha", 90},
{"Kiran", 80}
};
for(int i = 0; i < 2; i++) {
printf("%s %d\n", s[i].name, s[i].marks);
}
return 0;
}

Output

Asha 90
Kiran 80

4. Structure with User Input

#include <stdio.h>

struct Student {
char name[50];
int age;
};
int main() {
struct Student s1;

printf("Enter name: ");


scanf("%s", [Link]);

printf("Enter age: ");


scanf("%d", &[Link]);

printf("Name: %s\n", [Link]);


printf("Age: %d\n", [Link]);

return 0;
}

Sample Output

Enter name: Vidhya


Enter age: 21
Name: Vidhya
Age: 21

5. Structure with Function

#include <stdio.h>
struct Student {
int marks;
};
void display(struct Student s) {
printf("Marks: %d\n", [Link]);
}
int main() {
struct Student s1 = {95};
display(s1);
return 0;
}

Output

Marks: 95

You might also like