Note: This is a beta release of Red Hat Bugzilla 5.0. The data contained within is a snapshot of the live data so any changes you make will not be reflected in the production Bugzilla. Also email is disabled so feel free to test any aspect of the site that you want. File any problems you find or give feedback here.
Bug 163188 - setting const variables inside a vararg does not change them at -O1 and -O2
Summary: setting const variables inside a vararg does not change them at -O1 and -O2
Alias: None
Product: Fedora
Classification: Fedora
Component: gcc
Version: 4
Hardware: All
OS: Linux
Target Milestone: ---
Assignee: Jakub Jelinek
QA Contact:
Depends On:
TreeView+ depends on / blocked
Reported: 2005-07-13 21:11 UTC by Dan Williams
Modified: 2007-11-30 22:11 UTC (History)
1 user (show)

Fixed In Version:
Doc Type: Bug Fix
Doc Text:
Clone Of:
Last Closed: 2005-07-14 07:52:22 UTC

Attachments (Terms of Use)

Description Dan Williams 2005-07-13 21:11:27 UTC
See the testcase.  bar starts as -1, but should be 42 after calling foo(), even
though its const.  You could argue that bar shouldn't be const since we are
modifying it, but even so, the behavior should not be different at -O0 than -O1/2.

# gcc quux.c -O0 -o quux
# ./quux
Success: bar is 42

# gcc quux.c -O2 -o quux
# ./quux
Error: bar is not 42!  (it is -1)


#include <stdarg.h>
#include <stdio.h>

void foo (int n_args, ...)
    va_list qux;
    int *bar;

    va_start (qux, n_args);
    bar = va_arg (qux, int *);
    *bar = 42;

int main (int argc, char **argv)
    const int bar = -1;

    foo (1, &bar);
    if (bar != 42)
        printf ("Error: bar is not 42!  (it is %d)\n", bar);
        printf ("Success: bar is 42\n");
    return 0;

Comment 1 Dan Williams 2005-07-13 21:12:37 UTC
Testcase fails at -O1 and -O2 on both:


Comment 2 Jakub Jelinek 2005-07-14 07:52:22 UTC
The testcase is simply invalid, you must not modify a const variable.
The compiler is free to assume it is not modified (that is the purpose of
the const modifier, right?), but does not have to.  You simply trigger an
undefined behaviour and anything can happen at that point.

Note You need to log in before you can comment on or make changes to this bug.