cc1plus segfaults when using deeply recursive template definitions

Bug #1063415 reported by Neal Patel on 2012-10-07
This bug affects 1 person
Affects Status Importance Assigned to Milestone
gcc-4.6 (Ubuntu)

Bug Description

I didn't see this bug when I searched, so I apologize if it is a duplicate. cc1plus segfaults when I (ab)use recursive template definitions. Take a look at the offending code below, which I placed in a file called test.cpp.

#include <iostream>

template <int N>
void print()
   print<N - 1>();
   std::cout << N << std::endl;

template <>
void print<0>()

int main()
   return 0;

Building without -ftemplate-depth, the compiler gives an error, as expected.

neal@OK:~/Desktop$ g++ test.cpp -o test
test.cpp: In function ‘void print() [with int N = 998977]’:
test.cpp:7:4: error: template instantiation depth exceeds maximum of 1024 (use -ftemplate-depth= to increase the maximum) instantiating ‘void print() [with int N = 998976]’
test.cpp:7:4: recursively instantiated from ‘void print() [with int N = 999999]’
test.cpp:7:4: instantiated from ‘void print() [with int N = 1000000]’
test.cpp:18:19: instantiated from here

Building with -ftemplate-depth=1000000 causes a segfault.

neal@OK:~/Desktop$ g++ test.cpp -o test -ftemplate-depth=1000000
g++: internal compiler error: Segmentation fault (program cc1plus)
Please submit a full bug report,
with preprocessed source if appropriate.
See <file:///usr/share/doc/gcc-4.6/README.Bugs> for instructions.

According to the 2003 standard, the recursive template limit is implementation defined. I understand that there is a machine limit to the possible depth of a template definition, and that nobody in their right mind would write code like this. However, instead of having the code just segfault (which produces no useable error message), you should try to terminate gracefully.

Here is some more system information.

neal@OK:~/Desktop$ lsb_release -rd
Description: Ubuntu 12.04.1 LTS
Release: 12.04

neal@OK:~/Desktop$ apt-cache policy g++
  Installed: 4:4.6.3-1ubuntu5
  Candidate: 4:4.6.3-1ubuntu5
  Version table:
 *** 4:4.6.3-1ubuntu5 0
        500 precise/main amd64 Packages
        100 /var/lib/dpkg/status

ProblemType: Bug
DistroRelease: Ubuntu 12.04
Package: gcc-4.6 4.6.3-1ubuntu5
ProcVersionSignature: Ubuntu 3.2.0-31.50-generic 3.2.28
Uname: Linux 3.2.0-31-generic x86_64
ApportVersion: 2.0.1-0ubuntu13
Architecture: amd64
Date: Sun Oct 7 16:28:26 2012
EcryptfsInUse: Yes
InstallationMedia: Ubuntu 12.04.1 LTS "Precise Pangolin" - Release amd64 (20120823.1)
 PATH=(custom, user)
SourcePackage: gcc-4.6
UpgradeStatus: No upgrade log present (probably fresh install)

Neal Patel (nealp9084) wrote :
Neal Patel (nealp9084) wrote :
To post a comment you must log in.
This report contains Public information  Edit
Everyone can see this information.

Other bug subscribers