我将指针参数传递给函数,调用函数和被调用函数中的指针值不同。为了给出一个想法,我正在编写一段与我的工作代码类似的代码 -
void free_wrapper (char* a) {
printf ("a - %p \n", a);
free (a);
}
main () {
char a [200];
char * c = malloc (sizeof (char)*100); //some 100 bytes;
memset (a, 50, 200);
a [199] = '\0';
/* here I write some data into the alloc'ed memory */
/* instead of writing 100 bytes I go and write beyond the boundaries */;
strcpy (c, a); //explicit use of strcpy
printf ("c - %p \n", c);
free_wrapper (c);
return 0;
}
当我损坏分配的内存时,我看到 free_wrapper 之前的 printf 和 free_wrapper 中的 printf 正在打印不同的指针值。
我在此处提供的代码可能不会出现此问题,但我的工作代码经常遇到此问题。有人可以告诉我不同的场景,其中作为堆栈上的参数传递的值被损坏吗?
抱歉,打错字了,问题已更正。
最佳答案
I see that the printf before free_wrapper and the printf in the free_wrapper are printing different values for the pointer.
您将a
传递给free_wrapper
,但在它之前您写的是c
,而不是a
!
那是因为它们不同。
关于C 中的堆栈变量损坏,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12355880/