#include <stdio.h>
#include <string.h>
#define SRC_BUFF_SIZE 32
#define DST_BUFF_SIZE 8
int tempfn1(char *p)
{
printf("p %p\n", p);
return 0;
}
int tempfn(char *ip, int size)
{
char pttt[DST_BUFF_SIZE];
printf("ip %p\n", ip);
tempfn1(ip);
// ERROR - copying more data to a local buffer of 4 bytes
//memcpy(pttt, ip, size); // This will lead to stack corruption as
// the size exceeds the size of destination
// IDEALLY the copy should be done with min of size of destination buffer
// or source size rather than source size...
// anyways dest can hold only the size so it is better to crop the buffer
// than to crash due to overflow.
// proper call is as follows
#define MIN(a,b) (((a) < (b)) ? (a) : (b))
memcpy(pttt, ip, MIN(size, DST_BUFF_SIZE));
printf("ip %p\n", ip);
tempfn1(ip);
return 0;
}
int main()
{
char ip[SRC_BUFF_SIZE] = {0xe2, 0xe2, 0xe2, 0xe2, 0xe2, 0xe2, 0xe2, 0xe2,
0xe2, 0xe2, 0xe2, 0xe2, 0xe2, 0xe2, 0xe2, 0xe2,
0xe2, 0xe2, 0xe2, 0xe2, 0xe2, 0xe2, 0xe2, 0xe2,
0xe2, 0xe2, 0xe2, 0xe2, 0xe2, 0xe2, 0xe2, 0xe2 };
tempfn(ip, SRC_BUFF_SIZE);
return 0;
}
这是一个避免堆栈损坏的示例程序。是否有其他函数来检查目标的长度以及源以避免堆栈损坏?c中的堆栈损坏
通常情况下,你不应该让在明确的工作“避免堆栈损坏”。你应该正确编程。 – 2012-08-08 09:46:52
请注意,您必须**将'%p'的参数强制转换为'void *'以避免未定义的行为。 – Jens 2012-08-08 09:55:34