| | |
free() = delete or delete[]?
Please support our C++ advertiser: Intel Parallel Studio Home
![]() |
Hi there C /C++ experts...
I have a confusion regarding the function free(void *) in C and delete in C++. Suppose there is a pointer named p. In C++, we dynamically allocate memory for p to point at like this ,then when we use , in typical situations only the memory space for p[0] gets deallocated. And when we use p then all the memory space from p[0] to p[9] gets deallocated. I know that in C we use calloc() and malloc() to allocate memory dynamically and use free() to dellocate. Now, is this free() equivalent to delete or delete[]? That is does it deallocate memory space for only p[0] or all the memory space from p[0] to p[9]?????
I have a confusion regarding the function free(void *) in C and delete in C++. Suppose there is a pointer named p. In C++, we dynamically allocate memory for p to point at like this
C++ Syntax (Toggle Plain Text)
p = new int [10].
C++ Syntax (Toggle Plain Text)
delete p
C++ Syntax (Toggle Plain Text)
delete[] p
In the case you describe, delete p and delete [] p are the same as far as free() goes, but some runtimes would complain if you dont put in [].
The [] means that the compiler should call the 'vector delete' destructor, which calls the destructor on each element of the array. delete with no brackets just calls the destructor. In other words...
"delete p"
means:
p->~int(); // call the destructor of the object, in this case an int, so it may be skipped by the compiler, but you get the idea...
free(p); // free the space
"delete [] p"
means
for (int i = 0; i < (allocatedsizeof(p) / sizeof(p)); i++)
p[i].~int(); // destruct the ith object
free(p);
(allocatedsizeof() I made up to mean "the allocated memory size of the pointer()")
So the space allocated by either is always the same, its the destructor calling that is the difference. Some compilers/runtimes track whether an allocate was for a single object or an array, so you need to match your new [] with delete [], even for things like ints that don't have destructors.
The [] means that the compiler should call the 'vector delete' destructor, which calls the destructor on each element of the array. delete with no brackets just calls the destructor. In other words...
"delete p"
means:
p->~int(); // call the destructor of the object, in this case an int, so it may be skipped by the compiler, but you get the idea...
free(p); // free the space
"delete [] p"
means
for (int i = 0; i < (allocatedsizeof(p) / sizeof(p)); i++)
p[i].~int(); // destruct the ith object
free(p);
(allocatedsizeof() I made up to mean "the allocated memory size of the pointer()")
So the space allocated by either is always the same, its the destructor calling that is the difference. Some compilers/runtimes track whether an allocate was for a single object or an array, so you need to match your new [] with delete [], even for things like ints that don't have destructors.
Do you think it actually matters?!
If you have:
It prints 23. The same thing applies for delete[]. Why bother deallocating it?
I have a question of my own!
If you use:
It works very well. I DON'T get it!!! a is but a pointer and it doesn't point to anything. Even so it works. For strings, if this declaration is used: char *s,*s2; you may ask if (*s==*s2) .... You can also read it with gets and write it with puts. WHY??
If you have:
C++ Syntax (Toggle Plain Text)
int a=new int[8]; a[0]=23; delete a; cout<<a[0];
It prints 23. The same thing applies for delete[]. Why bother deallocating it?
I have a question of my own!
If you use:
C++ Syntax (Toggle Plain Text)
int *a,n,i=0; printf("%i",&n) for (i;i<n;i++) a[i]=i; for (i=0;i<n;i++) printf("%i ",a[i]);
It works very well. I DON'T get it!!! a is but a pointer and it doesn't point to anything. Even so it works. For strings, if this declaration is used: char *s,*s2; you may ask if (*s==*s2) .... You can also read it with gets and write it with puts. WHY??
It's probably bcos u r using a compilers like TURBO C/C++ IDE in DOS mode. The thing is if a pointer(automatic) is not initialized to point to something then it generally contains "garbage values". When u try to store some values to the place pointed by the pointer it actually tries to store the values in that "garbage" address. Now, run time errors will occur if u r using windows based compilers like visual c++. Bcos the place the pointer points to can be very much out of the memory space or resolution delivered to the program. Hence, an memory fault should happen.
And yes a[0] prints 23. Bcos deallocating doesnt delete everything that is contained in that "to be deallocated" memory space. What it actually does is that it makes this memory space available to other applications. If u do not free dynamically allocated memory then the space will always be kept for the program itself and this will not allow other applications to use the memory. Everytime u run a program having a dynamic allocation of memory and do not free the memory then each time u execute the program u lose certain amount of sytem memory gradually, which is referred to as memory leaking.
And even if u have "deallocated" that memory to be pointed by pointer a, the address a points to is still the same. Therefore,a[0] yields the same value, but that is bcos no other application has overwritten anything so far in the address of a[0], which can be used by applications other than ur program at anytime after it has been deallocated. Again, trying to access a[0] after the memory space for a[0] has been deallocated should result in a runtime error in any windows based compiler.
By the way, these are JUST my PURE speculation. Dont bliv anything i said unless verified by other "c/c++ techies" here. I dont even have any visual c++ or devc++. I am still doin my work in Turbo c++ IDE.
And yes a[0] prints 23. Bcos deallocating doesnt delete everything that is contained in that "to be deallocated" memory space. What it actually does is that it makes this memory space available to other applications. If u do not free dynamically allocated memory then the space will always be kept for the program itself and this will not allow other applications to use the memory. Everytime u run a program having a dynamic allocation of memory and do not free the memory then each time u execute the program u lose certain amount of sytem memory gradually, which is referred to as memory leaking.
And even if u have "deallocated" that memory to be pointed by pointer a, the address a points to is still the same. Therefore,a[0] yields the same value, but that is bcos no other application has overwritten anything so far in the address of a[0], which can be used by applications other than ur program at anytime after it has been deallocated. Again, trying to access a[0] after the memory space for a[0] has been deallocated should result in a runtime error in any windows based compiler.
By the way, these are JUST my PURE speculation. Dont bliv anything i said unless verified by other "c/c++ techies" here. I dont even have any visual c++ or devc++. I am still doin my work in Turbo c++ IDE.
Last edited by Asif_NSU; Jul 4th, 2004 at 1:46 pm. Reason: typo
To chainsaw,
I havent fully understood what u said, bcos I am halfway through C and now I have to make transition to C++ bcos my course wants me to do so. I dont have crystal clear concept like how delete or delete[] works. So could u bear the pain of explaining what free does in terms of my C knowledge? that would be much appreciated.
I havent fully understood what u said, bcos I am halfway through C and now I have to make transition to C++ bcos my course wants me to do so. I dont have crystal clear concept like how delete or delete[] works. So could u bear the pain of explaining what free does in terms of my C knowledge? that would be much appreciated.
TO Asif_NSU:I must admit that in Dev C++ this doesn't work at all. BUT in the DOS version it WORKS very well. I'm using Borlamd C++ 3.1. This thing is highly useful for ME. I will be in the 8th form next year and the compilers used at the Programming Olymphiad are for DOS. Therefor this will work. To ALL C/C++ (FOR DOS) programmers WHY am I allowed to do this???????(see 3rd post) :eek:
>WHY am I allowed to do this???????
You are not allowed to do this. Undefined behavior is, well, undefined behavior. It could behave how you think is "correct", it could crash, it could something completely different.
Now I'll admit, if all undefined behavior required something hideously harsh like reformatting your hard drive, programmers would learn very quickly what not to do. But this kindness granted to us by language implementors should not be overlooked.
You are not allowed to do this. Undefined behavior is, well, undefined behavior. It could behave how you think is "correct", it could crash, it could something completely different.
Now I'll admit, if all undefined behavior required something hideously harsh like reformatting your hard drive, programmers would learn very quickly what not to do. But this kindness granted to us by language implementors should not be overlooked.
"One of the methods used by statists to destroy capitalism consists in establishing controls that tie a given industry hand and foot, making it unable to solve its problems, then declaring that freedom has failed and stronger controls are necessary." --Ayn Rand
To Asif_NSU:
You asked again what free() does. Here's some code....
You asked again what free() does. Here's some code....
C++ Syntax (Toggle Plain Text)
char* p1 = new char[100]; char* p2 = malloc(100); // p1 and p2 both point to 100 charactors of allocated memory. Those calls were functionally idenctical in that sense. delete [] p1; free(p2); // Both of those calls deleted the 100 chars of ram allocated; again they are functionally identical. Here's where they're different: class AThingy { public: AThingy() { printf("Constructor\n"); } ~AThingy() { printf("Destructor\n"); } }; AThingy *t1 = new AThingy[100]; AThingy *t2 = (AThingy*)malloc( sizeof(AThingy) * 100 ); // now t1 and t2 both point to 100 thingys. However, the new [] call called the constructor of each of the 100 thingys, but malloc did not! delete [] t1; free(t2); // the delete [] called the destructor for all 100 items, the free did not! // so malloc-->new, free-->delete.
![]() |
Similar Threads
- Cant delete avi movie file! HELP (Windows NT / 2000 / XP)
- delete computer history (Windows NT / 2000 / XP)
- dubble delete (C++)
Other Threads in the C++ Forum
- Previous Thread: Problem with dispalying the output...
- Next Thread: C++ vector erase
| Thread Tools | Search this Thread |
api array arrays beginner binary bitmap c++ c/c++ calculator char char* class classes coding compile compiler console conversion convert count data database delete desktop developer directshow dll dynamic email encryption error file forms fstream function functions game generator getline google graph homeworkhelper iamthwee ifstream input int integer java lib linkedlist linker linux loop looping loops map math matrix memory multiple news node number numbertoword output parameter pointer problem program programming project proxy python random read recursion recursive reference return rpg sorting string strings struct template templates test text tree unix url vector video visualstudio win32 windows winsock word wordfrequency wxwidgets






