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 256 views
2 answers 215 views
3 answers 222 views
1 answer 158 views
158 views asked May 20, 2025 by avibootz
3 answers 240 views
3 answers 259 views
259 views asked May 20, 2025 by avibootz
1 answer 134 views
134 views asked May 20, 2025 by avibootz
...