函数调用时指针更改大小(使用 gdb 检查)
我有一个程序,它传递一个字符指针和传递它的函数以用字符串填充它。但是,我注意到数据被截断了。使用 gdb 进行调查后发现,指针的大小似乎存在差异。
int main(void) {
unsigned char *test_char;
test_char = (unsigned char *)malloc(sizeof(unsigned char) * 6);
memset(test_char, 0x00, sizeof(unsigned char) * 6);
functionToPopulate(test_char);
}
void functionToPopulate(unsigned char *test_char) {
snprintf(test_char, sizeof(test_char), "%u%s%u", 20, ":", 30);
}
在这种情况下,我在memset之前使用了gdb,并打印了test_char的值。它说(6)。在 snprintf 期间和之后,我再次使用 gdb 打印 test_char 的值。它说(4)。然而,返回后,该值再次显示 (6)。然而,数据已经被截断。它不再是“20:30”,而是“20:”。
I have a program that passes a character pointer and the function that it is passed on to populates it with strings. However, I noticed that the data were truncated. Upon investigation using gdb, it seems that there is a difference in the size of the pointers.
int main(void) {
unsigned char *test_char;
test_char = (unsigned char *)malloc(sizeof(unsigned char) * 6);
memset(test_char, 0x00, sizeof(unsigned char) * 6);
functionToPopulate(test_char);
}
void functionToPopulate(unsigned char *test_char) {
snprintf(test_char, sizeof(test_char), "%u%s%u", 20, ":", 30);
}
In this situation, I used gdb before memset, and printed the value of test_char. It says (6). During and after snprintf, I used gdb again to print the value of test_char. It says (4). However, upon return, the value says (6) again. However, the data has already been truncated. Instead of "20:30", it becomes "20:".
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
在调用
functiontopopulate
之前,您调用malloc sizeof(unsigned char) * 6
,它返回 6 sizeof(unsigned char) 是 1 * 6= 6。在函数内部,您调用 sizeof (test_char) 的大小是 (unsigned char *) 指针的大小为 4。当您需要在 c 中传递数组时,您必须始终传递数组的大小,因为 c 不维护它。Before the call to
functiontopopulate
you callmalloc sizeof(unsigned char) * 6
which returns 6 sizeof(unsigned char) is 1 * 6= 6. Inside the function you call sizeof(test_char) which is the size of a (unsigned char *) the size of the pointer is 4. When you need to pass an array in c you must always pass the size of the array as c does not maintain it.