Home > Back-end >  The following program malloc address why is the same?
The following program malloc address why is the same?

Time:10-07

The following program malloc address why is the same? While in blocking CreatList (int n) (p==NULL) then no problem, hope great god answer, thank you,
//-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --

# # ifndef ListH
# define ListH
#include
#include
#include

Typedef int Type.
Typedef struct node
{
Type data.
Struct node * Next;
} the List, * pList;

The class CList
{
Private:
Int Length;
Public:
CList ()
{
Length=0;
}
The List * CreatList (int n)
{
PList p=NULL, r=NULL, l=NULL;
for(int i=1; i<=n; I++)
{
While (p==NULL)
{
P=(List *) malloc (sizeof (List));
Printf (" % d \ n ", p);
}
P - & gt; Data=https://bbs.csdn.net/topics/i;
P - & gt; Next=NULL;
If (l==NULL)
{
L=p;
}
The else
{
R - & gt; Next=p;
}
R=p;

}
Length=n;
Return the l;
}

};


# endif

CodePudding user response:

CreatList in applying for multiple addresses, don't add the judgment

CodePudding user response:

Ha ha, your p pointer initialized outside the for loop only once, after the first distribution, it is not NULL, so in the back of the loop will no longer into the while allocating new memory, so it seems like every time
Solution is before every time into the while p to initialized to NULL, or simply don't have to assign malloc whether successful test, because in general is assigned a success, if you don't succeed, distribution of cycles is useless, isn't a programmer can control
  • Related