Common mistakes in C programming
Common mistakes about subfunction: 1. Formal parameter issues: void GetMemory(char *p) { p = (char *)malloc(100); } void Test(void) { char *str = NULL; GetMemory(str); strcpy(str, "hello world"); printf(str); } Using a pointer variable as formal parameter is dangerous, because formal parameter only passes the value. So it only pass the address. So when allocate memory to formal paramter or any other defined pointer variables in subfunction, it will disapear after the end of subfunction. Insteadly, we can achieve the same function by passing the pointer variable who points the pointer variable who is going to be allocated. void GetMemory2(char **p, int num) { *p = (char *)malloc(num); if(*p==NULL) printf(" Memory allocation fails!\n "); } void Test(void) { char *str = NULL; GetMemory(&str, 100); strcpy(str, "hello"); printf(str); } 2. Variable life in subfunction: ...