Wrong memory access with strlen() #2

Bug #1035321 reported by Removed by request
6
Affects Status Importance Assigned to Milestone
gcc-4.7 (Ubuntu)
New
Undecided
Unassigned

Bug Description

I'm using Ubuntu 12.10 dev with libc6 2.15-0ubuntu16 and valgrind 1:3.7.0-0ubuntu3. After the old bug was fixed (https://bugs.launchpad.net/ubuntu/+source/eglibc/+bug/839001) there is now a new bug which has a little different condition to trigger. It appears on -O3 and -O2 but not on -O1 (like the old bug).

Here is a new code example (compiled with "gcc -O3 -Wall -Wextra -o test -pedantic test.c" and executed with "valgrind ./test"):

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main()
{
 char *buffer1, buffer2[] = "1234";

 buffer1 = malloc(11);
 sprintf(buffer1, "123456%s", buffer2);
 fprintf(stdout, "%li\n", strlen(buffer1));
 free(buffer1);
 return 0;
}

This is the output from Valgrind:

==14601== Memcheck, a memory error detector
==14601== Copyright (C) 2002-2011, and GNU GPL'd, by Julian Seward et al.
==14601== Using Valgrind-3.7.0 and LibVEX; rerun with -h for copyright info
==14601== Command: ./test
==14601==
==14601== Invalid read of size 4
==14601== at 0x400623: main (in /home/sworddragon/data/test)
==14601== Address 0x51ef048 is 8 bytes inside a block of size 11 alloc'd
==14601== at 0x4C2B6CD: malloc (in /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so)
==14601== by 0x4005EA: main (in /home/sworddragon/data/test)
==14601==
10
==14601==
==14601== HEAP SUMMARY:
==14601== in use at exit: 0 bytes in 0 blocks
==14601== total heap usage: 1 allocs, 1 frees, 11 bytes allocated
==14601==
==14601== All heap blocks were freed -- no leaks are possible
==14601==
==14601== For counts of detected and suppressed errors, rerun with: -v
==14601== ERROR SUMMARY: 1 errors from 1 contexts (suppressed: 2 from 2)

Revision history for this message
Adam Conrad (adconrad) wrote :

If this is occurring only at higher optimisation levels, it's probably a GCC bug, but a GLIBC one.

affects: eglibc (Ubuntu) → gcc-4.7 (Ubuntu)
To post a comment you must log in.
This report contains Public information  
Everyone can see this information.

Other bug subscribers

Remote bug watches

Bug watches keep track of this bug in other bug trackers.