🔧malloc and calloc for Strings in C

🔹 Why Use Them?

You use malloc and calloc to allocate memory dynamically—especially useful when:


✅ Syntax

char* str = (char*) malloc(size_in_bytes);
char* str = (char*) calloc(num_elements, size_of_each);

💡 calloc also zero-initializes the memory, unlike malloc.


✅ Example 1: malloc

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

int main() {
    int len = 20;
    char* str = (char*)malloc(len * sizeof(char));

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

    strcpy(str, "Dynamic Hello");
    printf("String: %s\\n", str);

    free(str);  // ⚠️ Always free dynamically allocated memory
    return 0;
}

✅ Example 2: calloc

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

int main() {
    int len = 30;
    char* str = (char*)calloc(len, sizeof(char));  // zero-initialized

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

    strcat(str, "Using calloc");
    printf("String: %s\\n", str);

    free(str);
    return 0;
}

🧠 Challenge: Count Words in a Sentence (Using fgets, malloc, String functions)

💡Intuition