Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,851 questions

51,772 answers

573 users

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 184 views
184 views asked May 19, 2025 by avibootz
3 answers 153 views
2 answers 114 views
3 answers 135 views
1 answer 85 views
85 views asked May 20, 2025 by avibootz
3 answers 155 views
...