Thread: malloc function

Threaded View

Previous Post Previous Post   Next Post Next Post
  1. #1
    Registered User
    Join Date
    Sep 2018
    Posts
    9

    malloc function

    Im learning the dynamic storage allocation functions and I have a question about why this is happening. I made a function my_malloc that takes my request in bytes as argument and should return a pointer to the block of memory. And I wanted to allocate space for an array of 10 numbers, so it should be 40 bytes right? After the call of my_malloc, when I check the sizeof of the new array it tells me that has 8 bytes, so having a length of 2 elements. When I initialize the array to 100 elements(more than what I asked for) there is no error or something..
    Code:
    #include <stdio.h>
    #include <stdlib.h>
    
    void *my_malloc(int n);
    
    int main(void)
    {
        int *p, len;
        
        printf("my malloc request: %d bytes\n",(int)(10 * sizeof(int)));
        
        p = my_malloc(10 * sizeof(int));
        
        printf("Values after my_malloc call:\n\n"
               "size p: %d bytes\n", (int)sizeof(p));
        
        for(int i = 0; i < 100; i++) //Initializing all elements of p in 1
            p[i] = 1;
        
        len = sizeof(p)/sizeof(int);
        printf("len: %d\n", len);
        
        for(int i = 0; i < 100; i++) //printing the array
            printf("%d ", p[i]);
        printf("\n");
        
        len = sizeof(p)/sizeof(int);
        
        printf("len: %d\n", len);
        printf("size p: %d bytes\n", (int)sizeof(p));
        printf("\n");
        
        return 0;
    }
    
    void *my_malloc(int n)
    {
        void *p = malloc(n);
        printf("Values inside my_malloc:\n\n"
                "n : %d\n", n);
        printf("size p : %d bytes\n\n",(int)sizeof(p));
        if (p == NULL) {
            printf("malloc failed in my_malloc function.\n");
            exit(EXIT_FAILURE);
        } else
            return p;
    }
    malloc function-captura-de-pantalla-de-2019-04-27-14-13-48-jpg

    Can someone please explain me what's happening here? and/or what i'm doing wrong?
    Last edited by Griffith; 04-27-2019 at 11:22 AM.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. malloc function
    By Nikosant03 in forum C Programming
    Replies: 3
    Last Post: 02-10-2019, 02:24 PM
  2. malloc in function
    By mugen in forum C Programming
    Replies: 13
    Last Post: 03-14-2010, 11:27 AM
  3. malloc function
    By roaan in forum C Programming
    Replies: 9
    Last Post: 08-14-2009, 04:48 AM
  4. using malloc in a function
    By cuizy in forum C Programming
    Replies: 10
    Last Post: 08-13-2009, 01:56 PM
  5. about malloc function
    By enes in forum C Programming
    Replies: 1
    Last Post: 01-27-2002, 09:33 AM

Tags for this Thread