How to allocate 1MB in C#

3 Answers

0 votes
using System;

public class Program
{
    public static void Main(string[] args)
    {
        byte[] buffer = new byte[1024 * 1024]; // 1MB = 1,048,576 bytes
        
        Console.WriteLine("Allocated 1MB of memory.");
    }
}



/*
run:

Allocated 1MB of memory.

*/

 



answered May 19, 2025 by avibootz
0 votes
using System;
using System.IO;

class Program
{
    static void Main()
    {
        using MemoryStream ms = new MemoryStream(new byte[1024 * 1024]); // 1MB = 1,048,576 bytes
        
        Console.WriteLine("Allocated 1MB using MemoryStream.");
    }
}



/*
run:

Allocated 1MB using MemoryStream.

*/

 



answered May 19, 2025 by avibootz
0 votes
using System;
using System.Runtime.InteropServices;

class Program
{
    static void Main()
    {
        // Allocate 1MB = 1,048,576 bytes in unmanaged memory
        IntPtr ptr = Marshal.AllocHGlobal(1024 * 1024); 
        Console.WriteLine("Allocated 1MB of unmanaged memory.");
        
        Marshal.FreeHGlobal(ptr); // Free memory after use
    }
}



/*
run:

Allocated 1MB of unmanaged memory.

*/

 



answered May 19, 2025 by avibootz

Related questions

3 answers 429 views
2 answers 338 views
3 answers 372 views
1 answer 266 views
266 views asked May 20, 2025 by avibootz
3 answers 430 views
3 answers 411 views
411 views asked May 20, 2025 by avibootz
1 answer 222 views
222 views asked May 20, 2025 by avibootz
...