Monday, June 28, 2010

malloc(0), why is it working ?

1: #include <stdio.h>
2: #include <malloc.h>
3: 
4: char* reverse(char *data);
5: void my_Strcpy(char* dest,char* source);
6: main()
7: {
8:   char* p_Name = "Mithun P";
9:   char a_Name[] = "Mithun P";
10:   char *pd_Name = malloc(0);
11:   my_Strcpy(pd_Name,"Mithun P");
12:   
13: //printf("reverse of p_Name is %s \n",reverse(p_Name));
14:   printf("reverse of a_Name is %s \n",reverse(a_Name));
15:   printf("reverse of pd_Name is %s \n",reverse(pd_Name));
16:   
17:   getchar();
18: }
19: 
20: void my_Strcpy(char* dest,char* source)
21: {
22:   while(*dest++ = *source++);
23: }
24: 
25: char* reverse(char * data)
26: {
27:   int size = 0;
28:   int i,j;
29:   char* temp = data;
30:   while(*temp++)
31:     size++;
32:     
33:   printf("size is %d\n",size);
34:   
35:   for(i = 0, j = size-1;i < size/2; i++ , j--)
36:   {
37:     char temp = data[i];
38:     data[i] = data[j];
39:     data[j] = temp;
40:   }
41:   
42:   return data;
43: }


  1. the malloc(0) is returning a pointer to some memory location
  2. when the program access some memory using this pointer (pd_Name), which is not of its own, the program crashes
  3. tried on both VC++ and GCC, using the following loop 
    1:   while(pd_Name)
    
    2:     printf("%c %d",*pd_Name++,size++);

  4. on debug configuration the program crashes after accessing 9343B(cl) and 10031B(gcc)
  5. so the conclusion, if something like this happens the program may work mysteriously, and crashes unexpectedly

No comments: