#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;
}
这是一个避免堆栈损坏的示例程序。是否有任何其他功能可以检查目标长度和源长度以避免堆栈损坏?