Esben Mose Hansen <k...@mosehansen.dk> writes:

> this program SEGFAULTs
>
> #include <algorithm>
>
> int main() {
>   int numbers[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9 };
>   const std::size_t nn = sizeof(numbers)/sizeof(int);
>   int sum = 0;
>   int f = 5;
>   std::for_each(&numbers[0], &numbers[nn],  [&]  (int n)  { 
>     sum += n * f; 
>   });
>
> }
>
> Now, my assembly days are some 15 years past, but the disassembly is
>
> 0x08048424 <_ZZ4mainENK9__lambda0clEiz+0>:      push   %ebp
> 0x08048425 <_ZZ4mainENK9__lambda0clEiz+1>:      mov    %esp,%ebp
> 0x08048427 <_ZZ4mainENK9__lambda0clEiz+3>:      mov    0x8(%ebp),%eax
> 0x0804842a <_ZZ4mainENK9__lambda0clEiz+6>:      mov    0x4(%eax),%eax
> 0x0804842d <_ZZ4mainENK9__lambda0clEiz+9>:      mov    0x8(%ebp),%edx
> 0x08048430 <_ZZ4mainENK9__lambda0clEiz+12>:     mov    0x4(%edx),%edx
> 0x08048433 <_ZZ4mainENK9__lambda0clEiz+15>:     mov    (%edx),%ecx
> 0x08048435 <_ZZ4mainENK9__lambda0clEiz+17>:     mov    0x8(%ebp),%edx
> 0x08048438 <_ZZ4mainENK9__lambda0clEiz+20>:     mov    (%edx),%edx
> 0x0804843a <_ZZ4mainENK9__lambda0clEiz+22>:     mov    (%edx),%edx
> 0x0804843c <_ZZ4mainENK9__lambda0clEiz+24>:     imul   0xc(%ebp),%edx
> 0x08048440 <_ZZ4mainENK9__lambda0clEiz+28>:     lea    (%ecx,%edx,1),%edx
> => SEGFAULT 0x08048443 <_ZZ4mainENK9__lambda0clEiz+31>:     mov    %edx,(%eax)
> 0x08048445 <_ZZ4mainENK9__lambda0clEiz+33>:     pop    %ebp
> 0x08048446 <_ZZ4mainENK9__lambda0clEiz+34>:     ret
>
> I have marked the segfault spot. I also find 0x0804843a suspicious, but then 
> I 
> don't even know how to print register values in gcc. 
>
> Any pointers to where I should dig? I am completely new to gcc hacking, just 
> dying to get lambda into gcc 4.5 :)
>
> P.S: Shouldn't gcc show the actual lambda function code ( sum+= f*c; ) 
> instead 
> of the assembly code in any case?

When I try to specify the capture it works ((&sum, &f) works too but f is 
const):

#include <algorithm>

int
main(void)
{
  int numbers[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9 };
  const std::size_t nn = sizeof(numbers)/sizeof(int);
  int sum = 0;
  int f = 5;

  //std::for_each(&numbers[0], &numbers[nn], [&](int n) { sum += n * f; });

  std::for_each(&numbers[0], &numbers[nn], [&sum, f](int n) { sum += n * f; });

  return 0;
}

Reply via email to