gpt4 book ai didi

c - C中双指针的使用

转载 作者:行者123 更新时间:2023-11-30 21:19:07 25 4
gpt4 key购买 nike

void main() {
struct buf *head = NULL;
foo(&head);
}

void foo(struct buf **ptr_B) {
struct buf **ptr_A = ptr_B;
*ptr_B = NULL;
*ptr_A = malloc(sizeof(struct buff));
//here checked *ptr_A != NULL, so malloc is done successfully
if (*ptr_A == NULL) {
return;
}
*ptr_B->item = 8;
}

是否有可能*ptr_B仍然等于NULL?

我运行了一个自动检查工具,它总是在这里发出警告,说这是 *ptr_B->item = 8; 行中的前向空风险

最佳答案

我们来分析一下代码:

    struct buf **ptr_B;
// advance 1 stack slot for ptr_B, ptr_B value wasnot initialized
struct buf **ptr_A = ptr_B;
// advance 1 stack slot for ptr_A, set ptr_A by value of ptr_B (uninitialized)

*ptr_B = NULL;
// dereference ptr_B (ptr_B uninitialized) and set that memory block into NULL
*ptr_A = malloc();
// dereference ptr_A (ptr_A uninitialized) and set that memory block into malloc()
*ptr_B->item = 8;
// dereference ptr_B (ptr_B uninitialized, *ptr_B uninitialized) and use it as "struct buf"

正确代码:

    struct buf **ptr_B;
struct buf **ptr_A;

// allocate a pointer of `struct buf*` for both `ptr_A` and `ptr_B` point to
struct buf** temp_ptr1 = malloc(sizeof(struct buf*));
ptr_A = temp_ptr1;
ptr_B = temp_ptr1;

// set the shared pointer to NULL
*ptr_B = NULL;

// malloc
struct buf* temp_ptr2 = malloc(sizeof(struct buf*));
*ptr_A = temp_ptr2;

// Set value from `ptr_B`
(*ptr_B)->item = 8;

// clean up
free(*ptr_B);
free(ptr_B);

关于c - C中双指针的使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57701846/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com