Discussion: Strange seg fault
Afficher un message
Vieux 06/02/2008, 19h50   #2
Alf P. Steinbach
Aucun Avatar
 
Messages: n/a
Hébergeur:
Par défaut Re: Strange seg fault

* ciccio:
> Hi,
>
> Recently some people I know stumbled upon a strange problem with the
> following piece of code. This is reduced as far as possible.
>
> The idea of the code is simple. There are four structs of which one
> contains the other three structs. If we allocate a large double array
> of that struct and try to initialize it to zero, or try to use one of
> them in a function. The program gives a seg fault. If we make the array
> slightly smaller, there is no problem. The problem only appears on
> x86_64 architectures.
>
> Below I past a copy of the failing code. If DATAMAX is set to 4820 the
> program works, if it is set to 4830 it seg faults.
>
> What could the reason be of this? We have calculated the amount of
> memory and we have for sure no problem with that.


Are you sure?

Check

sizeof( Data[ISOMAX][DATAMAX] );

No need to calculate when you can check directly.

You're talking automatic local memory here, a.k.a. "stack". It may be
implemented in ways that give you very little elbow room. E.g. onboard
cache, registers.

Try dynamic allocation, which is easily achieved by using std::vector or
e.g. some library matrix class.



> A backtrace also does not give any deeper insight.
>
> #define DATAMAX 4830
> #define ISOMAX 7


In C++ it's a good idea to simply use typed constants, in order to avoid
macros,

size_t const maxData = 4830;



> typedef struct
> {
> short iso;
> char observable[15];
> short ds_dt;
> short ds_du;
> double emin;
> double emax;
> double cos;
> double ampli;
> double error;
> short tch;
> } Photo;


In C++ this is better expressed as

struct Photo
{
// ...
};


[snip]

> int main(int argc, char* argv)
> {
> // WORKS ALWAYS
> Data datapoints[ISOMAX][DATAMAX];


Maybe it's optimized away.


> // FAILS WITH DATAMAX = 4830 or larger
> // Data datapoints[ISOMAX][DATAMAX] = {{{0}}};
>
> // FAILS WITH DATAMAX = 4830 or lager
> // Data datapoints[ISOMAX][DATAMAX];
> // test(datapoints[0][0]);
>
> return 0;
> }



Cheers, & hth.,

- Alf


--
A: Because it messes up the order in which people normally read text.
Q: Why is it such a bad thing?
A: Top-posting.
Q: What is the most annoying thing on usenet and in e-mail?
  Réponse avec citation
 
Page generated in 0,05649 seconds with 9 queries