Returns the difference between "pointer to a String constant" and "Return array name ".
char*getmemory(void){ char p[]=”hello world”; return p;}void test(void){ char *str=NULL; str=getmemory(); printf(str);}
Q: What are the results of running the Test function?
Since array p is the data on the stack, the returned array name is the address of the stack memory, that is, the dynamic data zone, and the function is released at the end. Therefore, the returned address points to an uncertain position, str becomes garbled!
If changed:
char*getmemory(void){ char *p=”hello world”; return p;}void test(void){ char *str=NULL; str=getmemory(); printf(str);}
The output is correct because the pointer to the String constant is returned, which is the address of the static data zone (constant zone) and can be printed correctly!
Next question:
Q: The following program is used to output "Welcome to Huawei Test". Please note the two errors.
char * GetWelcome(void){ char * pcWelcome; char * pcNewWelcome; pcWelcome="Welcome to Huawei Test"; pcNewWelcome=(char *)malloc(strlen(pcWelcome)); //1 if(NULL==pcNewWelcome){ return NULL; //2 } strcpy(pcNewWelcome, pcWelcome); //3 return pcNewWelcome; //4}
Some people may think the answer is 1 and 4. They think that the address of the returned stack memory will be released except for the function. This is obviously wrong!
The correct answer is 1 and 3.
No memory is allocated to "\ 0" at 1st, and cannot be copied because "\ 0" cannot be copied at 3rd!
Since this function returns the address of the constant area, correct printing is acceptable!