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.

#include <stdio.h>

char* reverse(char *data);
void my_Strcpy(char* dest,char* source);
main()
{
	char* p_Name = "Mithun P";
	char a_Name[] = "Mithun P";
	char *pd_Name = malloc(0);//what is happening here
	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;
}

The short answer is that you are getting lucky. According to the standard, if the size of the data requested in malloc is 0, the result is implementation-defined. In your case, it appears to be allocating a small block of memory -- it's also legal for the compiler to return NULL, or to crash your computer (although that last is probably not very desirable!).

It's entirely possible, by the way, that you're writing over other memory that has been allocated to your program; this kind of error can be very hard to detect in more complex cases. At the very least, you should check the return value of malloc and do something different if it's NULL. I wouldn't expect this code to work in all environments.

commented: Good explaination :) +28
commented: Nice :) +8
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.