C - malloc allocating too much memory

前端 未结 3 806
小蘑菇
小蘑菇 2021-01-27 00:39

running int a strange scenario where malloc is allocating more memory than I ask for:

void function (int array [], int numberOfElements) {

int *secondArray = ma         


        
相关标签:
3条回答
  • 2021-01-27 00:41

    You are just lucky. Malloc can and sometimes does ask from more memory off the OS - Taking into account paging. Sometimes it does not even need to ask the OS for memory as it has asked for extra earlier. Therefore the malloc could ask for a page of memory - more that enough to satisfy your request and the extra memory happens to be filled with zeros.

    You are in the land of undefined behaviour. So all bets are off.

    0 讨论(0)
  • 2021-01-27 00:42

    malloc is actually allocating exactly the right amount.

    However, you're accessing memory beyond the allocation.

    What exists there is completely undefined and could really be anything.

    In your case, it was one "junk" number and four zeroes.

    0 讨论(0)
  • 2021-01-27 01:05
    /** its print 0 0 0 0 because in C no array bound if you define your array 
     * size is 4 but 
     * you want to store data more than array size you can store so you print your 
     * array.
     * for(i = 0; i < numberOfElements; i++) its give data and 0 also because you 
     * store the data 
     * only 5 position but you print it max size so it give you 0 0 0 
     */
        int *secondArray = malloc(sizeof(int) * numberOfElements/2); // no matter either use it or
        int *secondArray = malloc(sizeof(int));
        // ^^^ this will take same memory
    
    0 讨论(0)
提交回复
热议问题