Array invocation in C language--chaotic memory management

Source: Internet
Author: User

In the C language you want to create an array only by itself malloc or calloc, and the array copy is memcpy.

The array created in this way will not detect the bounds of the array at the time of invocation, that is, you declare an array of length 5, but you can access the 6th position ... You can also assign a value to the 7th position ...
I don't know if this is a memory leak, can you steal the information in memory in this way?

Cases:

int main () {int *list= (int*) malloc (5*sizeof (int));  for (int i=0;i<5;++i) {list[i]=i;  } for (int i=0;i<15;++i) {cout<<list[i]<<endl; } free (list);}

I assign 5 positions to the list and assign values, but the call can be completely ignored by the array length limit to see the 6th position and even the nth position.

If you use malloc at the time of assignment and do not delete the original memory data, then some "random number" is output, is it the data in the original memory?

MEMCPY also does not consider the boundary, I can copy a length of 20 array to a length of 5 array, and then the length of the array length of 5 becomes 20 ...

Cases:

int main () {int* list= (int*) malloc (10*sizeof (int)); int * list2= (int*) malloc (5*sizeof (int)); for (int i=0;i<20;i++) { List[i]=i;} memcpy (list2,list,20*sizeof (int)); for (int i=0;i<20;++i) {cout<<i<< "" <<list2[i]<<endl;} Free (list), free (LIST2);}

Note that the list only declares memory with a length of 10, but it assigns 20 values.

List2 declaration length is 5, but also copied into 20 values, no error can be normal operation.

So ... What does it mean to declare memory ... There is no limit to the length of the whole AH! Will that overwrite the other memory data?

It feels so messed up ~

Array invocation in C language--chaotic memory management

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.