C language: a typical case involving the garbled and memory stack of the pointer function returned value and printf
A strange C language problem involves pointers, arrays, stacks, and printf. The following implementation: converts Integers to strings, returns string pointers, and CALLS printf in the main function for display.
#include
#include
#include
char* swich(int n)
{
char A[20],B[20];
char*p;//=(char*)malloc(4*sizeof(char));
int i=0,a;
int minus=0;
if(n<0)
{
minus=1;
n=-n;
}
while(n/10!=0)
{
a=n%10;
n=n/10;
A[i++]='0'+a;
}
a=n%10;
A[i++]='0'+a;
if(minus==1)
A[i++]='-';
A[i]=0;
int len=i;
int j=len-1;
i=0;
while(i
{
B[i]=A[len-1-i];
i++;
}
B[i]=0;
p=B;
printf("%s,",p);
return p;
}
void main()
{
int a=-234;
char* p=swich(a);
char b[10];
strcpy(b,p);
int i=0;
printf("%s,",b);
}
The execution result of the preceding program is as follows: In the swich function, 234 can be output normally. The output in main is garbled.
for(int i=0;i<3;i++)
{
printf("%c",p[i]);
}
Then only '2' can be correctly output, p [1], p [2] garbled.
Why? Before calling the function printf, you must press the form parameter on the stack. * p is calculated at this time. Therefore, the first printf statement has calculated the parameters and saved them on the top of the stack. Then call the printf function (the function call needs to use the stack to establish an access connection and control chain. The original function f is executed, and the original function f is at the top of the stack. Therefore, the stack space of function f is released. Array space is also released), printf occupies the stack, so the original function f stack space content is modified. Therefore, the first printf statement can obtain the result. Since the content of the arr space has been modified, subsequent printf statements cannot get the result.
By the way, I will explain why printf ("% s \ n", p); is garbled.
As mentioned above, calculate the value of parameter p to save the stack top. The saved value is the address of arr. Then call the printf function to modify the content of the top stack space. Although the address is saved, the original content has been modified, so no result is obtained.
Source: >