我将一个指针参数传递给一个函数,调用函数和被调用函数中的指针值不同。为了让一个想法,我写了一段代码,看起来类似于我的工作代码 -C中的损坏堆栈变量
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 free_wrapper前的printf和printf的打印不同指针的值。
这个问题可能不会发生在我在这里介绍的代码,但我经常用我的工作代码打它。有人可以给我一些不同场景的想法,其中作为堆栈参数传递的值会被破坏吗?
对不起,错字已被更正。
“当我损坏分配的内存”<---不要破坏它!问题解决了! –