#1
  1. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Jun 2013
    Posts
    142
    Rep Power
    2

    Question on memory allocation


    when I ran this program
    Code:
    /* Program 9.2 from PTRTUT10.HTM   6/13/97 */
    
    #include <stdio.h>
    #include <stdlib.h>
    
    int main(void)
    {
        int nrows = 5;     /* Both nrows and ncols could be evaluated */
        int ncols = 10;    /* or read in at run time */
        int row;
        int **rowptr;
        rowptr = malloc(nrows * sizeof(int *));
        if (rowptr == NULL)
        {
            puts("\nFailure to allocate room for row pointers.\n");
            exit(0);
        }
    
        printf("\n\n\nIndex   Pointer(hex)   Pointer(dec)   Diff.(dec)");
    
        for (row = 0; row < nrows; row++)
        {
            rowptr[row] = malloc(ncols * sizeof(int));
            if (rowptr[row] == NULL)
            {
                printf("\nFailure to allocate for row[%d]\n",row);
                exit(0);
            }
            printf("\n%d         %p         %d", row, rowptr[row], rowptr[row]);
            if (row > 0)
            printf("              %d",(int)(rowptr[row] - rowptr[row-1]));
        }
    
        return 0;
    }
    the difference was 12 bytes each.
    I expected 40 bytes, since each row contains 10 ints.
    Please help me understand this.
  2. #2
  3. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Jan 2010
    Posts
    13
    Rep Power
    0
    The difference is given in units of "int" not bytes; there is room for 12 ints between the pointers malloc returns. that's 48 bytes, if size_of(int)=4. The extra 8 bytes are presumably used by the machinery behind malloc to keep whatever it wants to keep track of for the area you allocated. For instance, it might include the size of the memory chunk allocated for later use by free().

IMN logo majestic logo threadwatch logo seochat tools logo