C - malloc allocating too much memory

前端 未结 3 929
小蘑菇
小蘑菇 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 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
    

提交回复
热议问题