How to allocate 1MB in C

1 Answer

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

int main() {
    size_t bytes = 1024 * 1024; // 1MB = 1,048,576 bytes
    char *buffer = (char *)malloc(bytes);

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

    // Use the allocated memory (e.g., initialize it)
    for (size_t i = 0; i < bytes; i++) {
        buffer[i] = 0; // Initialize all bytes to 0
    }

    printf("Memory allocated and initialized successfully.\n");

    // Free the allocated memory
    free(buffer);

    return 0;
}



/*
run:

Memory allocated and initialized successfully.

*/

 



answered May 19, 2025 by avibootz

Related questions

2 answers 219 views
1 answer 84 views
1 answer 74 views
2 answers 196 views
2 answers 357 views
2 answers 147 views
147 views asked May 19, 2025 by avibootz
3 answers 201 views
...