How to allocate 1MB in C++

2 Answers

0 votes
#include <iostream>

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

    // Use the memory (example: initialize to zero)
    for (int i = 0; i < bytes; i++) {
        buffer[i] = 0;
    }
    
    std::cout << "Memory allocated and initialized successfully.\n";

    // Free the memory
    delete[] buffer;
}



/*
run:

Memory allocated and initialized successfully.

*/

 



answered May 19, 2025 by avibootz
0 votes
#include <vector>
#include <iostream>

int main() {
    size_t bytes = 1024 * 1024; // 1MB = 1,048,576 bytes
    
    std::vector<char> buffer(bytes, 0);

    // Use the memory 
    buffer[0] = 'Z';

    // No need to manually free memory; vector handles it automatically
    
    std::cout << "Memory allocated and initialized successfully.\n";
}



/*
run:

Memory allocated and initialized successfully.

*/

 



answered May 19, 2025 by avibootz

Related questions

1 answer 227 views
227 views asked May 19, 2025 by avibootz
3 answers 202 views
2 answers 152 views
3 answers 180 views
1 answer 131 views
131 views asked May 20, 2025 by avibootz
3 answers 197 views
...