Total Pageviews

Tuesday, December 2, 2025

calloc 2

 //calloc


#include <stdio.h>

#include <stdlib.h> 

int main() {

    int *ptr;

    int n = 5;

    printf("Enter number of values:\n");

    scanf("%d",&n);

    

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


    if (ptr == NULL) {

        printf("Memory allocation failed!\n");

        return 1; 

    }


   

    printf("\n");


   

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

        ptr[i] = i *10+10;

    }


    printf("After assigning values:\n");

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

        printf("%d ", ptr[i]); 

    }

    printf("\n");


   

    free(ptr);

    ptr = NULL; 


    return 0;

}


i

Output

After assigning values:
10 20 30 40 50

🟦 Step 9: Free the Allocated Memory

free(ptr);

Explanation

The free() function releases the dynamically allocated memory.

Before free():

ptr


+-----+-----+-----+-----+-----+
| 10 | 20 | 30 | 40 | 50 |
+-----+-----+-----+-----+-----+

After free():

Memory Released to the Operating System

The memory is no longer available for use.


🟦 Step 10: Assign NULL to the Pointer

ptr = NULL;

Why?

After calling free(), the pointer still contains the old memory address.

Such a pointer is called a dangling pointer.

Assigning NULL makes the pointer safe.

Before

ptr



0x7ffab120

After

ptr



NULL

📊 Program Flow Diagram

Start


Read n


Allocate Memory using calloc()


Is ptr == NULL?

┌─┴───────────────┐
│ │
Yes No
│ │
▼ ▼
Print Error Store Values
Exit │

Print Values


Free Memory


ptr = NULL


End

🖥 Sample Execution

Input

Enter number of values:
5

Output

After assigning values:
10 20 30 40 50

📦 Memory Representation

Before Allocation

ptr



NULL

After calloc()

ptr



+----+----+----+----+----+
| 0 | 0 | 0 | 0 | 0 |
+----+----+----+----+----+

After Storing Values

ptr



+----+----+----+----+----+
|10 |20 |30 |40 |50 |
+----+----+----+----+----+

After free()

Memory Released

ptr



NULL

🌟 Advantages of calloc()

  • ✅ Allocates memory dynamically during program execution.
  • ✅ Initializes all allocated memory to 0.
  • ✅ Helps avoid using uninitialized data.
  • ✅ Suitable when the number of elements is known only at runtime.

⚠ Precautions

  • Always check whether calloc() returns NULL.
  • Always access elements within the allocated range (0 to n-1).
  • Always call free() when the memory is no longer needed.
  • Set the pointer to NULL after free() to avoid dangling pointers.

Tuesday, November 25, 2025

Calloc

 //calloc


#include <stdio.h>

#include <stdlib.h> 

int main() {

    int *ptr;

    int n = 5;

    printf("Enter number of values:\n");

    scanf("%d",&n);

    

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


    if (ptr == NULL) {

        printf("Memory allocation failed!\n");

        return 1; 

    }


   

    printf("\n");


   

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

        ptr[i] = i *10+10;

    }


    printf("After assigning values:\n");

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

        printf("%d ", ptr[i]); 

    }

    printf("\n");


   

    free(ptr);

    ptr = NULL; 


    return 0;

}



🟦 Step 1 : Include Header Files

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

📖 Explanation

📚 Header File🎯 Purpose
🟦 stdio.hUsed for input/output functions like printf() and scanf().
🟩 stdlib.hUsed for dynamic memory functions such as calloc(), malloc(), realloc(), and free().

🟦 Step 2 : Start the Program

int main()

📖 Explanation

Every C program begins execution from the main() function.

Program Starts


int main()

🟦 Step 3 : Declare Variables

int *ptr;
int n = 5;

📖 Explanation

VariableMeaning
🔹 ptrPointer that stores the address of dynamically allocated memory
🔹 nNumber of integer elements

Initially

ptr



NULL

n = 5

No memory has been allocated yet.


🟦 Step 4 : Take User Input

printf("Enter number of values:\n");
scanf("%d",&n);

Example Input

Enter number of values:
5

Now,

n = 5

🟦 Step 5 : Allocate Memory Using calloc()

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

📌 Syntax

calloc(Number_of_Elements, Size_of_Each_Element)

Example

n = 5

sizeof(int)=4 bytes

Memory allocated

5 × 4 = 20 Bytes

🖼 Memory Before Allocation

ptr



NULL

🖼 Memory After calloc()

ptr



+------+------+------+------+------+
| 0 | 0 | 0 | 0 | 0 |
+------+------+------+------+------+

⭐ Important

calloc() initializes every element to 0 automatically.


🟦 Step 6 : Check Memory Allocation

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

📖 Explanation

If the operating system cannot allocate memory,

ptr



NULL

The program prints

Memory allocation failed!

and terminates safely.


🟦 Step 7 : Store Values

for(int i=0;i<n;i++)
{
ptr[i]=i*10+10;
}

📊 Value Calculation

🔢 iFormulaStored Value
00×10+10✅ 10
11×10+10✅ 20
22×10+10✅ 30
33×10+10✅ 40
44×10+10✅ 50

🖼 Memory After Storing Values

ptr



+------+------+------+------+------+
| 10 | 20 | 30 | 40 | 50 |
+------+------+------+------+------+

🟦 Step 8 : Print the Values

printf("After assigning values:\n");

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

Output

After assigning values:

10 20 30 40 50

🟦 Step 9 : Release Memory

free(ptr);

📖 Explanation

The free() function releases the allocated memory back to the operating system.

Before free()

ptr



+------+------+------+------+------+
| 10 | 20 | 30 | 40 | 50 |
+------+------+------+------+------+

After free()

Memory Released

ptr



(Dangling Pointer)

The memory no longer belongs to the program.


🟦 Step 10 : Assign NULL

ptr=NULL;

📖 Explanation

After freeing memory, the pointer still contains the old address.

Such a pointer is called a Dangling Pointer.

Assigning

ptr=NULL;

makes the pointer safe.


Before

ptr



0x1000A520

After

ptr



NULL

🌈 Complete Memory Flow

🔹 Before Allocation

ptr



NULL

🔹 After calloc()

ptr



+----+----+----+----+----+
| 0 | 0 | 0 | 0 | 0 |
+----+----+----+----+----+

🔹 After Assigning Values

ptr



+----+----+----+----+----+
|10 |20 |30 |40 |50 |
+----+----+----+----+----+

🔹 After free()

Memory Released

ptr



NULL

🖥 Sample Run

Input

Enter number of values:
5

Output

After assigning values:

10 20 30 40 50

🌟 Advantages of calloc()

✅ Allocates memory dynamically.

✅ Initializes all memory to 0.

✅ Prevents uninitialized (garbage) values.

✅ Useful when array size is known only during program execution.


Malloc

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

    }

    printf("Memory successfully allocated using malloc.\n");

     printf("enter a value.\n");

    scanf("%d",ptr);   

        printf("value = %d ", *ptr);    

    printf("\n");

           return 0; 

}



🟦 Step 1 : Include Header Files

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

📖 Explanation

📚 Header File🎯 Purpose
🟦 stdio.hUsed for input/output functions like printf() and scanf().
🟩 stdlib.hUsed for memory management functions such as malloc(), calloc(), realloc(), and free().

🟦 Step 2 : Start the Program

int main()

📖 Explanation

Every C program begins execution from the main() function.

Program Starts


int main()

🟦 Step 3 : Declare a Pointer

int *ptr;

📖 Explanation

  • ptr is an integer pointer.
  • It will store the address of dynamically allocated memory.

Initially

ptr



Garbage Address (Uninitialized)

🟦 Step 4 : Allocate Memory Using malloc()

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

📌 Syntax

malloc(Number_of_Bytes)

Example

sizeof(int) = 4 bytes

Memory allocated

4 Bytes

🖼 Memory Representation

Before Allocation

ptr



?

After Allocation

ptr



+---------+
| Garbage |
+---------+

⭐ Important

Unlike calloc(), malloc() does NOT initialize memory.

The allocated memory contains garbage (unpredictable) values until you assign a value.


🟦 Step 5 : Check Memory Allocation

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

📖 Explanation

If memory allocation fails,

ptr



NULL

The program prints:

Memory allocation failed!

and terminates safely.


🟦 Step 6 : Display Success Message

printf("Memory successfully allocated using malloc.\n");

Output

Memory successfully allocated using malloc.

This confirms that memory allocation was successful.


🟦 Step 7 : Read a Value

printf("Enter a value:\n");
scanf("%d", ptr);

Suppose the user enters

25

The value 25 is stored in the allocated memory.


🖼 Memory Diagram

Before Input

ptr



+---------+
| Garbage |
+---------+

After Input

ptr



+------+
| 25 |
+------+

🟦 Step 8 : Print the Stored Value

printf("Value = %d", *ptr);

Explanation

*ptr means the value stored at the memory location pointed to by ptr.

If

ptr = 1000 (Address)

Memory

1000 → 25

Then

*ptr

returns

25

Output

Value = 25

🌈 Complete Memory Flow

🔹 Before Allocation

ptr



Uninitialized

🔹 After malloc()

ptr



+---------+
| Garbage |
+---------+

🔹 After User Input

ptr



+------+
| 25 |
+------+

🔹 After Printing

Value = 25

🖥 Sample Execution

Input

Enter a value:
50

Output

Memory successfully allocated using malloc.
Enter a value:
50
Value = 50

📊 malloc() Memory Representation

            malloc(sizeof(int))




+---------------+
ptr ------>| 25 |
+---------------+

🌟 Advantages of malloc()

✅ Allocates memory during program execution.

✅ Useful when memory size is determined at runtime.

✅ Efficient because it does not initialize memory.

✅ Widely used for dynamic arrays, linked lists, trees, and other dynamic data structures.


⚠ Best Practices

✔ Always check if malloc() returns NULL.

✔ Initialize the allocated memory before using it.

✔ Release allocated memory using free().

✔ After free(), assign the pointer to NULL.


🟦 Improved Version of the Program

Your program allocates memory correctly, but it should also release it after use.

free(ptr);
ptr = NULL;

Add these lines before return 0;.