可能重复:
将函数指针转换为另一种类型
假设我用一个函数初始化一个函数指针,该函数实际上比函数指针定义需要更少的参数,如果通过函数指针调用,函数是否仍能正确执行?
我尝试使用gcc,它按预期工作,但我想知道这种行为在编译器/平台上是否一致(我怀疑在某些环境中它可能会对堆栈造成严重破坏):
#include <stdio.h>
typedef void (*myfun)(int, int, int);
void test_a(int x, int y, int z) {
printf("test_a %d %d %d\n", x, y, z);
}
void test_b(int x, int y) {
printf("test_b %d %d\n", x, y);
}
int main() {
myfun fp;
fp = test_a;
fp(1, 2, 3);
fp = (myfun) test_b;
fp(4, 5, 6);
}
Run Code Online (Sandbox Code Playgroud) 我已经分配了一些内存,char* memoryChunk = malloc ( 80* sizeof(char) + 1);是什么阻止我写入超过81个单元的内存位置?我该怎么做才能防止这种情况发生?
void testStage2(void) {
char c_str1[20] = "hello";
char* ut_str1;
char* ut_str2;
printf("Starting stage 2 tests\n");
strcat(c_str1, " world");
printf("%s\n", c_str1); // nothing exciting, prints "hello world"
ut_str1 = utstrdup("hello ");
ut_str1 = utstrrealloc(ut_str1, 20);
utstrcat(ut_str1, c_str1);
printf("%s\n", ut_str1); // slightly more exciting, prints "hello hello world"
utstrcat(ut_str1, " world");
printf("%s\n", ut_str1); // exciting, should print "hello hello world wo", 'cause there's not enough room for the second world
} …Run Code Online (Sandbox Code Playgroud)