Thread: Memory to be deallocated

  1. #1
    Registered User
    Join Date
    Jan 2011
    Posts
    18

    Memory to be deallocated

    Hi All,
    I have written the following code.

    Code:
    #include <stdio.h>
    #include <stdlib.h>
    
    int main()
    {
            int *a, *b;
    
            a = (int*) malloc (sizeof(int) * 10);
    
            printf ("%d\n", a[-1]);
    
            b = (int*) malloc (sizeof(int) * 15);
    
            printf ("%d\n", b[-1]);
    
            return 0;
    }
    I have written many mallocs and printed the '-1' Index of the each allocated memory. The output for the previous one comes as follows:

    Code:
    49 65
    I have observed that it actually shows how much memory it has allocated.

    Code:
    For the 10(even) allocations, It allocates space for 
    10 Integers (4 * 10 = 40 bytes) + One 4 bytes space for -1 Index Itself + 1 (4 bytes) after the array 
    = 40 + 4 + 4 = 48
    And It adds 1 extra byte. (I don't know why?) Hence It prints = 49.

    Code:
    Similarly, for 15(odd) allocations, It allocates space for 
    15 Integers(4*15 = 60 bytes) + One 4 bytes space for -1 Index Itself = 60 + 4 = 64 bytes
    And It adds 1 extra byte. (I don't know why?) Hence It prints = 65.

    Why does It add an extra byte? This is my question.

    Thanks and Best Regards,
    Aakash Johari

  2. #2
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,660
    Why do you believe anything you've written?

    You have tested exactly ONE permutation of
    - Operating system ( type and version )
    - Compiler ( type and version )
    - Compiler options
    - Standard library version

    Change anything, and you're looking at
    - the same answer
    - a different answer
    - a segmentation fault

    Like your other thread, it is very machine dependent.

    If you really want to know what it actually is (rather than guess from a few experiments), then download the GlibC source code and read malloc.c
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 4
    Last Post: 01-13-2008, 02:14 AM
  2. Question regarding Memory Leak
    By clegs in forum C++ Programming
    Replies: 29
    Last Post: 12-07-2007, 01:57 AM
  3. Memory problem with Borland C 3.1
    By AZ1699 in forum C Programming
    Replies: 16
    Last Post: 11-16-2007, 11:22 AM
  4. Suggestions on this C style code
    By Joelito in forum C Programming
    Replies: 11
    Last Post: 06-07-2007, 03:22 AM
  5. Shared Memory - shmget questions
    By hendler in forum C Programming
    Replies: 1
    Last Post: 11-29-2005, 02:15 AM