C + + Error NOTE-If you want to free memory, you must get the first address of the memory to release

Source: Internet
Author: User

Example: Modifying the third letter of a string is a

#include <stdlib.h>#include<string.h>#include<stdio.h>#pragmaWarning (disable:4996)voidMain () {Char*p = (Char*)malloc( -); strcpy (P,"123456789"); P= p +2; *p ='a';  Free(P); System ("Pause");}

Run, VS reported the following error:

This problem occurs because the C language stipulates that if you want to release memory, you must get the first address of the memory to release it.

The P pointer is shifted before it is released and no longer points to the first address, so the program occurs crash. WORKAROUND: Simply save the address of the first element for release.

#include <stdlib.h>#include<string.h>#include<stdio.h>#pragmaWarning (disable:4996)voidMain () {Char*p = (Char*)malloc( -); strcpy (P,"123456789"); Char*pheader =p; P= p +2; *p ='a'; printf ("%s\n", Pheader);  Free(Pheader); System ("Pause");}

Operation Result:

C + + Error NOTE-If you want to free memory, you must get the first address of the memory to release

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.