Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
444 views
in Technique[技术] by (71.8m points)

c++ - Delete and invalid pointer

int main()
{
    char* a=new char[20];  
    cin>>a;  
    cout<<" character at 7-th position."<<a[6];  
    delete a+4;  
    cout<<a[0];
    return 0;
}

Input:

1234567894567 

Output:

character at 7-th position.6  
*** glibc detected *** ./test free() invalid pointer:....  

Now I have 3 questions

  1. Is it correct that delete a+4 will only delete the character at a+4?
  2. If answer to previous one is yes then what happens to a[0].We should get the output.
  3. to delete a chunk of memory we should write delete[].But in this case how come all the elements are deleted?
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

There are only three types of pointer values you can pass as the operand of delete:

  1. Null pointer values. They simply get ignored.
  2. A complete scalar (not array) object previously allocated with new, either of:
    • The exact pointer returned by new
    • A pointer to a base subobject of the pointer returned by new, if and only if the base subobject's type has a virtual destructor

Any these pointer values should NEVER ever be passed to scalar delete:

  1. The result of array new or new[] (use delete[] instead)
  2. The result of malloc or any other allocator which is not new
  3. The address of an object with automatic or static storage duration
  4. The address of a member subobject or array element
  5. Uninitialized pointer values
  6. Pointers to already-deleted objects

If you break this rule, you get undefined behavior. That means your program might crash with a nice message that an invalid delete was detected. Or your data might get corrupted, saved in your data files, sent to your boss, shown to the customer, and later you get fired. So don't break the rule.

Your code falls into category "NEVER DO THIS #4".


The reason it works this way is because an implementation can (and most do) track extra information called metadata along with each allocated block. For example, the size of the block, which is pretty important for enabling reuse. There is no metadata for part of a block, and there may not be any way to find the metadata from a pointer into the middle.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...