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 402 views
1 answer 185 views
1 answer 189 views
2 answers 403 views
2 answers 562 views
2 answers 319 views
319 views asked May 19, 2025 by avibootz
3 answers 418 views
...