what is malloc(0) doing ?

mpandey's Avatar
Newbie Member
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;
}
0
xpi0t0s's Avatar, Join Date: Aug 2004
Mentor
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.