C 中的堆栈变量损坏

标签 c function parameters

我将指针参数传递给函数,调用函数和被调用函数中的指针值不同。为了给出一个想法,我正在编写一段与我的工作代码类似的代码 -

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/

相关文章:

c - 使用 pipe、fork 和 exec 后程序挂起

c - 是否可以在初始化程序中使用三元运算符初始化静态数组?

c - Visual Studio 2013 C 语法概述

c++ - 是否可以在 C++ 中将函数作为参数传递?

更改我在 C 函数中传递的指针

c# - 如何将多个枚举传递给只接收一个的方法?

C# MySql 将数据库中特定行的参数从一种表单传递到另一种表单

function - Swift 方法中的多个未命名参数

c - 如何修改链表中的插入函数以适合所需的输出?

c - 在 C 中传递、编辑和返回变量