此代码取自:本lecture notes pdf第20-21页来自 OCW。
struct node∗ nalloc ( int data )
{
struct node∗ p=( struct node ∗) malloc ( sizeof (node )) ;
if ( p!=NULL) {
p−>data=data ;
p−>next=NULL;
}
return p;
}
struct node∗ addfront ( struct node∗ head , int data )
{
struct node∗ p= nalloc (data );
if ( p==NULL) return head ;
p−>next=head;
return p;
}
我认为代码是错误的,因为指针 p 是 nalloc() 的本地指针,并且在 addfront() 中使用它会产生未定义的行为。我见过the answer to this question并相信我是正确的,但有人可以验证吗?
最佳答案
函数是对的。但你的逻辑并没有那么错误。变量 p
实际上是本地变量,当函数返回时将不再存在。不过,p
并不是您用 malloc
分配的内存,而是一个存储您分配的内存地址的变量。
因此,语句return p;
将返回p
的副本,即您使用分配的内存地址的副本malloc()
。
在链接的问题中,用户创建一个本地数组并返回指向它的指针。看,该数组是本地的,现在使用new
或malloc()
动态分配。所以他的变量实际上包含(自动)分配的内存,而不是它的地址。但是,仅返回地址,因此内存丢失。
关于c - 这个addfront()函数与nalloc()一起用于链表是错误的吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59819470/