I am playing with the code  struct A {     char a[20000];     A() { a[0] = 'A'; }     ~A() {} }; struct B : A {     char a[20000];     B() { a[0] = 'B'; }     ~B() {} }; int main() {     A *pA = new A;     A *pB = new B;     delete pA;     delete pB;     return 0; }   Some people wrote () that it should cause a memory leak but it doesn't. I used g++, then valgrind --leak-check=full --show-leak-kinds=all --track-origins=yes --verbose --log-file=valgrind-out.txt and get   HEAP SUMMARY: in use at exit: 0 bytes in 0 blocks total heap usage: 3 allocs, 3 frees, 132,704 bytes allocated All heap blocks were freed -- no leaks are possible   I know that some old compilers had problems when they try to free memory in similar situations but it looks like that the modern C++ can free memory seamlessly in this case.  So I am curios how is it possible?  Maybe delete uses information provided by OS for a given allocated memory block?  EDIT.  It is still unclear for me what exactly can cause the UB for delete *pB if we have empty destructors and constructors.  An answer for a question () shows that there are no any UB.
3035
I have a solid understanding of most OOP theory but the one thing that confuses me a lot is virtual destructors. I thought that the destructor always gets called no matter what and for every object in the chain. When are you meant to make them virtual and why?
52849
So I have a pointer to an array of pointers.  If I delete it like this:  delete [] PointerToPointers;   Will that delete all the pointed to pointers as well?  If not, do I have to loop over all of the pointers and delete them as well, or is there an easier way to do it?  My google-fu doesn't seem to give me any good answers to this question.  (And yeah, I know I need to use a vector.  This is one of those "catch up on C++" type assignments in school.)
50435
What is the memory layout of a .NET array?  Take for instance this array:  Int32[] x = new Int32[10];   I understand that the bulk of the array is like this:  0000111122223333444455556666777788889999   Where each character is one byte, and the digits corresponds to indices into the array.  Additionally, I know that there is a type reference, and a syncblock-index for all objects, so the above can be adjusted to this:  ttttssss0000111122223333444455556666777788889999         ^         +- object reference points here   Additionally, the length of the array needs to be stored, so perhaps this is more correct:  ttttssssllll0000111122223333444455556666777788889999         ^         +- object reference points here   Is this complete? Are there more data in an array?  The reason I'm asking is that we're trying to estimate how much memory a couple of different in-memory representations of a rather large data corpus will take and the size of the arrays varies quite a bit, so the overhead might have a large impact in one solution, but perhaps not so much in the other.  So basically, for an array, how much overhead is there, that is basically my question.  And before the arrays are bad squad wakes up, this part of the solution is a static build-once-reference-often type of thing so using growable lists is not necessary here.
81862
Does string immutability work by statement, or by strings within a statement?   For example, I understand that the following code will allocate two strings on the heap.  string s = "hello "; s += "world!";   "hello" will remain on the heap until garbage collected; and s now references "hello world!" on the heap. However, how many strings does the following line allocate on the heap...1 or 2? Also, is there a tool/way to verify the results?  string s = "goodbye " + "cruel world!";
1982
The following code is generating a stack overflow error for me  int main(int argc, char* argv[]) {     int sieve[2000000];     return 0; }   How do I get around this? I am using Turbo C++ but would like to keep my code in C  EDIT:  Thanks for the advice.  The code above was only for example, I actually declare the array in a function and not in sub main.  Also, I needed the array to be initialized to zeros, so when I googled malloc, I discovered that calloc was perfect for my purposes.  Malloc/calloc also has the advantage over allocating on the stack of allowing me to declare the size using a variable.
13470
I am a little surprised by the following.  Example 1:  char s[100] = "abcd"; // declare and initialize - WORKS   Example 2:  char s[100]; // declare s = "hello"; // initalize - DOESN'T WORK ('lvalue required' error)   I'm wondering why the second approach doesn't work. It seems natural that it should (it works with other data types)? Could someone explain me the logic behind this?
84232
Alright, I think we all agree that what happens with the following code is undefined, depending on what is passed,  void deleteForMe(int* pointer) {      delete[] pointer; }   The pointer could be all sorts of different things, and so performing an unconditional delete[] on it is undefined. However, let's assume that we are indeed passing an array pointer,  int main() {      int* arr = new int[5];      deleteForMe(arr);      return 0; }   My question is, in this case where the pointer is an array, who is it that knows this? I mean, from the language/compiler's point of view, it has no idea whether or not arr is an array pointer versus a pointer to a single int. Heck, it doesn't even know whether arr was dynamically created. Yet, if I do the following instead,  int main() {      int* num = new int(1);      deleteForMe(num);      return 0; }   The OS is smart enough to only delete one int and not go on some type of 'killing spree' by deleting the rest of the memory beyond that point (contrast that with strlen and a non-\0-terminated string -- it will keep going until it hits 0).  So whose job is it to remember these things? Does the OS keep some type of record in the background? (I mean, I realise that I started this post by saying that what happens is undefined, but the fact is, the 'killing spree' scenario doesn't happen, so therefore in the practical world someone is remembering.)
94655
I was experimenting with C++ and found the below code as very strange.   class Foo{ public:     virtual void say_virtual_hi(){         std::cout &lt;&lt; "Virtual Hi";     }      void say_hi()     {         std::cout &lt;&lt; "Hi";     } };  int main(int argc, char** argv) {     Foo* foo = 0;     foo-&gt;say_hi(); // works well     foo-&gt;say_virtual_hi(); // will crash the app     return 0; }   I know that the virtual method call crashes because it requires a vtable lookup and can only work with valid objects.   I have the following questions    How does the non virtual method say_hi work on a NULL pointer? Where does the object foo get allocated?   Any thoughts?
46005
If I have a source.c file with a struct:  struct a {      int i;     struct b {         int j;     } };   How can this struct be used in another file (i.e. func.c)?  Should I create a new header file, declare the struct there and include that header in func.c?  Or should I define the whole struct in a header file and include that in both source.c and func.c?  How can the struct be declared extern in both files?  Should I typedef it? If so, how?
66029
I wrote C++ for 10 years. I encountered memory problems, but they could be fixed with a reasonable amount of effort.  For the last couple of years I've been writing C#. I find I still get lots of memory problems. They're difficult to diagnose and fix due to the non-determinancy, and because the C# philosophy is that you shouldn't have to worry about such things when you very definitely do.  One particular problem I find is that I have to explicitly dispose and cleanup everything in code. If I don't, then the memory profilers don't really help because there is so much chaff floating about you can't find a leak within all the data they're trying to show you. I wonder if I've got the wrong idea, or if the tool I've got isn't the best.  What kind of strategies and tools are useful for tackling memory leaks in .NET?
95859
Why does C/C++ differentiates in case of array index out of bound #include &lt;stdio.h&gt; int main() {     int a[10];     a[3]=4;     a[11]=3;//does not give segmentation fault     a[25]=4;//does not give segmentation fault     a[20000]=3; //gives segmentation fault     return 0; }  I understand that it's trying to access memory allocated to process or thread in case of a[11] or a[25] and it's going out of stack bounds in case of a[20000]. Why doesn't compiler or linker give an error, aren't they aware of the array size? If not then how does sizeof(a) work correctly?
19601
Does anyone have experience with using very large heaps, 12 GB or higher in Java?   Does the GC make the program unusable? What GC params do you use? Which JVM, Sun or BEA would be better suited for this? Which platform, Linux or Windows, performs better under such conditions? In the case of Windows is there any performance difference to be had between 64 bit Vista and XP under such high memory loads?
2864
In C++ the following code gives a compiler error:  void destruct1 (int * item) {   item-&gt;~int(); }   This code is nearly the same, I just typedef the int to another type and something magic happens:  typedef int myint;  void destruct2 (myint * item) {   item-&gt;~myint(); }   Why does the second code work? Does an int get a destructor just because it has been typedefed?  In case you wonder why one ever would like to do this: This comes from refactoring C++ code. We're removing the standard heap and replacing it with selfmade pools. This requires us to call placement-new and the destructors. I know that calling destructors for primitive types is useless, but we want them in the code nevertheless in case we later replace PODs with real classes.  Finding out that naked int's don't work but typedefed ones do was quite a surprise.  Btw - I have a solution that involves template-functions. We just typedef inside the template and everything is fine.
84371
In ANSI C, offsetof is defined as below.  #define offsetof(st, m) \     ((size_t) ( (char *)&amp;((st *)(0))-&gt;m - (char *)0 ))   Why won't this throw a segmentation fault since we are dereferencing a NULL pointer? Or is this some sort of compiler hack where it sees that only address of the offset is taken out, so it statically calculates the address without actually dereferencing it? Also is this code portable?
83585
I think I've got it down to the most basic case:  int main(int argc, char ** argv) {   int * arr;    foo(arr);   printf("car[3]=%d\n",arr[3]);   free (arr);   return 1; }  void foo(int * arr) {   arr = (int*) malloc( sizeof(int)*25 );   arr[3] = 69; }   The output is this:  &gt; ./a.out   car[3]=-1869558540  a.out(4100) malloc: *** error for object 0x8fe01037: Non-aligned pointer                          being freed  *** set a breakpoint in malloc_error_break to debug &gt;   If anyone can shed light on where my understanding is failing, it'd be greatly appreciated.
106456
Do you have to pass delete the same pointer that was returned by new, or can you pass it a pointer to one of the classes base types?  For example:  class Base { public:     virtual ~Base();     ... };  class IFoo { public:     virtual ~IFoo() {}     virtual void DoSomething() = 0; };  class Bar : public Base, public IFoo { public:     virtual ~Bar();     void DoSomething();     ... };  Bar * pBar = new Bar; IFoo * pFoo = pBar; delete pFoo;   Of course this is greatly simplified.  What I really want to do is create a container full of boost::shared_ptr and pass it to some code that will remove it from the container when it is finished. This code will know nothing of the implementation of Bar or Base, and will rely on the implied delete operator in the shared_ptr destructor to do the right thing.  Can this possibly work? My intuition says no, since the pointers will not have the same address.  On the other hand, a dynamic_cast&lt;Bar*> should work, so somewhere the compiler is storing enough information to figure it out.  Thanks for the help, everybody who answered and commented. I already knew the importance of virtual destructors, as shown in my example; after seeing the answer I gave it a little thought, and realized the whole reason for a virtual destructor is this exact scenario. Thus it had to work. I was thrown by the absence of a visible means of converting the pointer back to the original. A little more thinking led me to believe there was an invisible means, and I theorized that the destructor was returning the true pointer for delete to release. Investigating the compiled code from Microsoft VC++ confirmed my suspicion when I saw this line in ~Base:  mov eax, DWORD PTR _this$[ebp]   Tracing the assembler revealed that this was the pointer being passed to the delete function. Mystery solved.  I've fixed the example to add the virtual destructor to IFoo, it was a simple oversight. Thanks again to everyone who pointed it out.
113003
We are using the CString class throughout most of our code. However sometimes we need to convert to a char *. at the moment we have been doing this using variable.GetBuffer(0) and this seems to work ( this mainly happens when passing the Csting into a function where the function requires a char *). The function accepts this and we keep going.  However we have lately become worried about how this works, and whether there is a better way to do it.  The way i understand it to work is it passes a char pointer into the function that points at the first character in the CString and all works well.  I Guess we are just worried about memory leaks or any unforseen circumstances where this might not be a good idea.