what is malloc(0) doing ?

Discussion in 'C' started by mpandey, Jun 28, 2010.

  1. mpandey

    mpandey New Member

    Joined:
    Nov 13, 2009
    Messages:
    4
    Likes Received:
    0
    Trophy Points:
    0
    Home Page:
    http://howtoccpp.blogspot.com/
    I am doing malloc(0) and then doing strcpy and then reversing, and its working, why??
    and if i dont do malloc(0) and then try to strcpy program carashed as expected, but how does malloc(0) making a difference.

    Code:
    #include <stdio.h>
    #include <malloc.h>
    
    char* reverse(char *data);
    void my_Strcpy(char* dest,char* source);
    void main()
    {
        char* p_Name = "Mithun P";
        char a_Name[] = "Mithun P";
        char *pd_Name = (char*)malloc(0);
        my_Strcpy(pd_Name,"Mithun P");
        
    //    printf("reverse of p_Name is %s \n",reverse(p_Name));
        printf("reverse of a_Name is %s \n",reverse(a_Name));
        printf("reverse of pd_Name is %s \n",reverse(pd_Name));
        
        getchar();
    }
    
    void my_Strcpy(char* dest,char* source)
    {
        while(*dest++ = *source++);
    }
    
    char* reverse(char * data)
    {
        int size = 0;
        int i,j;
        char* temp = data;
        while(*temp++)
            size++;
            
        printf("size is %d\n",size);
        
        for(i = 0, j = size-1;i < size/2; i++ , j--)
        {
            char temp = data[i];
            data[i] = data[j];
            data[j] = temp;
        }
        
        return data;
    }
    
     
  2. xpi0t0s

    xpi0t0s Mentor

    Joined:
    Aug 6, 2004
    Messages:
    3,009
    Likes Received:
    203
    Trophy Points:
    63
    Occupation:
    Senior Support Engineer
    Location:
    England
    No idea. The program exhibits undefined behaviour. You must malloc the amount of memory you need. malloc(0), if it does anything, returns a pointer to memory that you haven't allocated, so you are overwriting something in use by someone else (you're no better off than just using a random number generator to get your pointer). If the program doesn't show any ill effects YET (because if you think malloc(0) "works" then you WILL eventually hit some major issues), that means you've by chance found a chunk of memory that isn't currently in use.
     

Share This Page

  1. This site uses cookies to help personalise content, tailor your experience and to keep you logged in if you register.
    By continuing to use this site, you are consenting to our use of cookies.
    Dismiss Notice