函数调用-C后指针值丢失
输出:10-但为所需值函数调用-C后指针值丢失,c,pointers,parameters,C,Pointers,Parameters,输出:10-但为所需值 printf("%d\n",*(ListHead->data)); 输出:0-在传递到遍历函数后,该值会随机丢失,即使在所有其他调用后它似乎被正确分配。指向非静态局部变量的指针从ReadAll()传递到insert(),并保存到新创建的节点 从ReadAll()返回并在调用未定义行为后取消引用指针后,此变量将不可用。这就是随机性的原因 为了避免这种情况,放置在节点上的指针应该指向即使从ReadAll()返回后仍然可用的对象 可以通过动态分配 printf("%d\
printf("%d\n",*(ListHead->data));
输出:0-在传递到遍历函数后,该值会随机丢失,即使在所有其他调用后它似乎被正确分配。指向非静态局部变量的指针从
ReadAll()
传递到insert()
,并保存到新创建的节点
从ReadAll()
返回并在调用未定义行为后取消引用指针后,此变量将不可用。这就是随机性的原因
为了避免这种情况,放置在节点上的指针应该指向即使从ReadAll()
返回后仍然可用的对象
可以通过动态分配
printf("%d\n",*(headptr->data));
或者使变量保持静态
void ReadAll(Node **headptr)
{
int *x = malloc(sizeof(int));
*x = 10;
insert(headptr, x);
}
而且,正如Peter指出的那样,Allocate()
的实现是错误的。
分配大小应该是
sizeof(Node)
,而不是sizeof(int)
您的代码中有几个问题:
在
*newnode
是一个节点*
,因此它必须是
void AllocateNode(Node **newnode)
{
*newnode = malloc(sizeof(int));
}
在
将x的地址指定为局部变量,以将其保存在节点中
通过该指针的所有访问都无效,并且在退出ReadAll时具有未指定的行为
一种可能性是分配int
在这些更正、汇编和执行之后:
void ReadAll(Node **headptr)
{
int * x = malloc(sizeof(int));
*x = 10;
insert(headptr, x);
}
瓦尔格林死刑
Allocate()
为int
分配足够的存储空间。但是,使用该内存的代码希望在那里有一个节点。如果sizeof(int)
则行为未定义。存储自动变量的地址,然后稍后取消对该指针的引用(另一种未定义行为的情况)。这对您没有帮助。您是否正在尝试创建一个链接列表?正如一些答案已经指出的,在释放后使用。您可以在这里通过对代码的实时测试看到它:实际上insert
应该接受int
而不是int*
*newnode
是节点*
,所以它所指的是节点
。因此大小应该是sizeof(Node)
,而不是sizeof(Node*)
@MikeCAT哦,是的,谢谢,该死的,我在答案中手工编辑代码时犯了两个错误,而不是复制/粘贴我的代码^^
void AllocateNode(Node **newnode)
{
*newnode = malloc(sizeof(int));
}
void AllocateNode(Node **newnode)
{
*newnode = malloc(sizeof(Node));
}
void ReadAll(Node **headptr)
{
int x = 10;
insert(headptr, &x);
}
void ReadAll(Node **headptr)
{
int * x = malloc(sizeof(int));
*x = 10;
insert(headptr, x);
}
vxl15036 /tmp % gcc -pedantic -Wextra -g l.c
vxl15036 /tmp % ./a.out
10
10
vxl15036 /tmp % valgrind ./a.out
==28709== Memcheck, a memory error detector
==28709== Copyright (C) 2002-2012, and GNU GPL'd, by Julian Seward et al.
==28709== Using Valgrind-3.8.1 and LibVEX; rerun with -h for copyright info
==28709== Command: ./a.out
==28709==
10
10
==28709==
==28709== HEAP SUMMARY:
==28709== in use at exit: 12 bytes in 2 blocks
==28709== total heap usage: 2 allocs, 0 frees, 12 bytes allocated
==28709==
==28709== LEAK SUMMARY:
==28709== definitely lost: 8 bytes in 1 blocks
==28709== indirectly lost: 4 bytes in 1 blocks
==28709== possibly lost: 0 bytes in 0 blocks
==28709== still reachable: 0 bytes in 0 blocks
==28709== suppressed: 0 bytes in 0 blocks
==28709== Rerun with --leak-check=full to see details of leaked memory
==28709==
==28709== For counts of detected and suppressed errors, rerun with: -v
==28709== ERROR SUMMARY: 0 errors from 0 contexts (suppressed: 6 from 6)