Wei dong
Wei dong

Reputation: 69

Have different result at different versions of gcc

Compare two codes as follow:

  1 #include <new>
  2 #include <cstdio>
  3 class CA
  4 {
  5 public:
  6     int i, j, k;
  7 };  
  8 
  9 int main()
 10 {
 11     int aa[4] = { 1, 2, 3, 4 };
 12     CA *i = new(aa) CA();
 13     printf("%d %d %d %d\n", aa[0], aa[1], aa[2], aa[3]);
 14     return 0;
 15 }   

  1 #include <new>
  2 #include <cstdio>
  3 class CA
  4 {
  5 public:
  6     int i, j, k;
  7 };  
  8 
  9 int main()
 10 {
 11     int aa[4] = { 1, 2, 3, 4 };
 12     CA *i = new(aa) CA;
 13     printf("%d %d %d %d\n", aa[0], aa[1], aa[2], aa[3]);
 14     return 0;
 15 }   

The difference at line 12. At environment of gcc4.1.2, these two codes will get the same result 1 2 3 4 But at gcc4.4 and gcc4.5, the first code will get 0 0 0 4

Why ?

Upvotes: 5

Views: 192

Answers (3)

MSalters
MSalters

Reputation: 179779

I'm inclined to think that both are correct. You've overwritten (part of) the memory used by int aa[4], and then try to access that array. That's not correct: the memory contains an CA object and must be accessed through that type or a compatible type. int [4] and class CA are not compatible types.

This rule is important: an optimizer might cache the value aa[0] in a register, and not reload the register when you put an object at the same memory address.

Upvotes: 0

sharptooth
sharptooth

Reputation: 170479

First of all, different versions of GCC have different levels of standard compliance.

In this case later versions are "more right" - value initialization must take place in the first snippet (since you implicitly invoke the default compiler-generated constructor for a class with POD member variables) and this will lead to member variables of class CA initialized to zeroes. See this very detailed answer by user Michael Burr as well as this answer to a closely related question.

Upvotes: 2

BЈовић
BЈовић

Reputation: 64193

That is placement new. You initialized an object of type CA into that memory, and the default values for the i,j and k are zeros, therefore aa[0], aa[1] amd aa[2] are getting zeroed.

Upvotes: 1

Related Questions