Go4Expert

Go4Expert (http://www.go4expert.com/)
-   C (http://www.go4expert.com/forums/c/)
-   -   what is malloc(0) doing ? (http://www.go4expert.com/forums/malloc-0-doing-t22579/)

mpandey 28Jun2010 22:19

what is malloc(0) doing ?
 
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;
}


xpi0t0s 29Jun2010 12:45

Re: what is malloc(0) doing ?
 
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.


All times are GMT +5.5. The time now is 13:05.