Home > Back-end >  Questions about the malloc function of memory, a great god to give directions
Questions about the malloc function of memory, a great god to give directions

Time:09-27

Application:
# include & lt; stdio.h>
# include & lt; Stdlib. H>


Struct student {
Char name [6].
Char xiaoname [6].
};

Typedef struct student students;

Void add_list (students * s1);

Int main ()
{
Students s1.
Add_list (& amp; S1);


Printf (" % s \ n ", s1, name);

system("pause");

return 0;
}

Void add_list (students * s1)
{
S1=(students *) malloc (sizeof (students));//can you tell me what happened here out of memory, can show here,
Gets_s (s1 - & gt; Name);
Gets_s (s1 - & gt; Xiaoname);

}

I feel thinking right ah, how the result is wrong U ah, a checked didn't understand the Internet,

CodePudding user response:

When not malloc overflow, but your gets_s input more than 6 characters, buffer bounds

CodePudding user response:

When malloc you don't succeed, to judge, and each secondary malloc remember free

CodePudding user response:


Students s1.
//s1 allocated on the stack, already do not need to allocate memory for its,
Add_list (& amp; S1);//pass here is that the object of s1 address, call add_list is values, there will be a temporary object, that is,
The equivalent of code:
Register students * TMP=& amp; S1.
Add_list (TMP);
So add_list function should not be allocated memory,

S1=(students *) malloc (sizeof (students));//can you tell me what happened here out of memory, can show here,
//this should not happen out of memory, seen from the above code, the line does not need to exist,
//here is there is a memory leak, that is, function, after the completion of the allocation of memory addresses will be discarded, unable to recycle the memory,
//is the following two sentences need to ensure that no overflow,
Gets_s (s1 - & gt; Name);
Gets_s (s1 - & gt; Xiaoname);
You give the name of xiaoname only 6 bytes, so can't more than 5 characters, otherwise the overflow (note the string terminator),

CodePudding user response:

Upstairs positive solution, NND BBS less than 6 characters don't let submit feedback,
  • Related