Bug 68888 - No Warning when converting an array of a subclass to its parent
Summary: No Warning when converting an array of a subclass to its parent
Status: NEW
Alias: None
Product: gcc
Classification: Unclassified
Component: c++ (show other bugs)
Version: 5.3.0
: P3 enhancement
Target Milestone: ---
Assignee: Not yet assigned to anyone
URL:
Keywords: diagnostic
Depends on:
Blocks: new-warning, new_warning
  Show dependency treegraph
 
Reported: 2015-12-14 00:45 UTC by Matt Corallo
Modified: 2021-10-27 05:14 UTC (History)
3 users (show)

See Also:
Host:
Target:
Build:
Known to work:
Known to fail:
Last reconfirmed: 2021-08-10 00:00:00


Attachments

Note You need to log in before you can comment on or make changes to this bug.
Description Matt Corallo 2015-12-14 00:45:50 UTC
Without bringing up the deadly "warn when using arrays in function declarations" quagmire, if you are converting an array of one type to that of another due to pointer decay, there should probably at least be a huge warning.

eg the following prints "1 2" to the surprise of many unthinking programmers.

#include <stdio.h>

class A {
public:
	int a;
};

class B : public A {
public:
	int b;
};

void go(A b[2]) {
	fprintf(stderr, "%d %d\n", b[0].a, b[1].a);
}

int main() {
	B bs[2];
	bs[0].a = 1;
	bs[0].b = 2;
	bs[1].a = 3;
	bs[1].b = 4;
	go(bs);
}
Comment 1 Jonathan Wakely 2021-08-10 10:25:42 UTC
This is undefined behaviour, and should definitely warn (and UBsan should give an error too).

The implicit conversion sequence of array-to-pointer decay followed by derived-to-base conversion should warn. If the derived-to-base conversion is really desired (because no pointer arithmetic will be done on the result) then users can get a pointer to the first element of the array explicitly, so there is no implicit decay e.g. any of these would not warn:

  go(&bs[0]);
  go(&*bs);
  go((B*)bs);
  go(std::begin(bs));

(of course the code would still have undefined behaviour due to the arithmetic in go, but it wouldn't warn because there's no implicit decay).
Comment 2 Eric Gallager 2021-10-27 05:14:07 UTC
Any ideas for a proposed name for the flag that would control this warning?