Search code examples
c++windowsmemory-leaksmalloclarge-data

why access memory error when malloc the size so large?


As this you can see, when I run it, I got memory access error .but if I change the malloc_size to 100,it can work. How to fix it without changing malloc_size.

int malloc_size = 900000;
float* ptr = (float *)malloc(malloc_size);


for (int i = 0; i< malloc_size; i ++) {

    ptr[i] = 0;
}

Solution

  • malloc accepts the amount of bytes to allocate as a parameter. Let's say your malloc_size was 100 for the sake of simplicity.

    The for loop iterating while i < malloc_size can exceed that limit because inside, you're accessing ptr[i] = 0;. ptr is a pointer to a float, which is most likely four bytes large. This means that ptr[i] accesses the byte at offset i * sizeof(float), or i * 4. When i reaches 25, you're accessing the byte at offset 25 * 4 = 100, which is one past the end.

    Accessing an array out of bounds is undefined behavior, and in your case, it leads to a program crash.

    C++ Advice

    Since this question is tagged , I also recommend not to use malloc at all. A much better alternative is new:

    float* ptr = new float[100] {}; // array of size 100
                                    // all elements are initialized to zero
    // ...
    delete[] ptr;
    

    You still have to manage memory manually with new and delete, so it would be much easier to use std::vector instead:

    #include <vector>
    // ...
    
    std::vector<float> vec(100); // vector of size 100
                                 // all elements are initialized to zero
    // no need to free/delete