函数调用时指针更改大小(使用 gdb 检查)

发布于 2025-01-06 01:44:38 字数 591 浏览 1 评论 0原文

我有一个程序,它传递一个字符指针和传递它的函数以用字符串填充它。但是,我注意到数据被截断了。使用 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

人事已非 2025-01-13 01:44:38

在调用 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 call malloc 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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文