What is the difference between delete and delete[] in C++?
2023
What is the difference between delete and delete[] in C++?
- A.
Delete is syntactically correct but delete[] is wrong and hence will give an error if used in any case
- B.
Delete is used to delete normal objects whereas delete[] is used to delete pointer objects
- C.
Delete is used to delete single object whereas delete[] is used to delete multiple (array/pointer of) objects
- D.
More than one of the above
- E.
None of the above
Attempted by 103 students.
Show answer & explanation
Correct answer: C
In C++, delete and delete[] are used to deallocate memory, but they are used in different contexts.
delete is used to deallocate memory for a single object that was allocated using new. For example:
int* ptr = new int(10);
delete ptr;delete[] is used to deallocate memory for an array that was allocated using new[]. For example:
int* arr = new int[5];
delete[] arr;Using delete on an array or delete[] on a single object results in undefined behavior, which may cause memory corruption or program crashes.
Therefore, the correct distinction is: delete for single objects, delete[] for arrays.
हिन्दी उत्तर:
C++ में delete और delete[] का उपयोग मेमोरी को वापस लेने के लिए किया जाता है, लेकिन वे अलग-अलग संदर्भों में उपयोग किए जाते हैं।
delete एक एकल ऑब्जेक्ट के लिए उपयोग किया जाता है जिसे new का उपयोग करके आवंटित किया गया है। उदाहरण के लिए:
int* ptr = new int(10);
delete ptr;delete[] एक ऐरे के लिए उपयोग किया जाता है जिसे new[] का उपयोग करके आवंटित किया गया है। उदाहरण के लिए:
int* arr = new int[5];
delete[] arr;एक ऐरे पर delete का उपयोग करना या एक एकल ऑब्जेक्ट पर delete[] का उपयोग करना अपरिभाषित व्यवहार का कारण बनता है, जिससे मेमोरी की क्षति या प्रोग्राम क्रैश हो सकता है।
इसलिए, सही अंतर यह है: delete एकल ऑब्जेक्ट्स के लिए, delete[] ऐरे के लिए।