Thanks for your help!
I traced the problem to the way values are assigned to an array in a structure:
Code:
#include <iostream>
#include <vector>
#include <string>
#include <cstdlib>
#include <ctime>
#include <cstddef>
using namespace std;
typedef struct {
string d; // Statistical distribution
int n; // Number of entries
double* dx; // x-values
double* dy; // y-values
double* dz; // z-values
} Distribution;
void seedRNG() {
srand(static_cast<unsigned>(time(0)));
}
void fill(Distribution& D, double x) {
*(D.dx + D.n) = x; // crash!!!!!
D.n++;
}
double l2Norm(double p1, double p2) {
return p1 - p2 >= 0 ? p1 - p2 : p2 - p1;
}
void poissonL2Norm(Distribution& D, int* ra) {
// poissonL2Norm
//
// Throw beans on a closed interval of width RAND_MAX+1
// and measure the distance between adjacent beans:
//
// Example:
// 0 RAND_MAX
// [--B---BB--- ... ---B--B]
// |< >||< >|<>|
//
// Width: 3 1 RAND_MAX-7 2
//
// Expected distribution: Poisson
//
// Efficiency: O(n)
// while(*(1+ra++));
fill(D, l2Norm(*ra, *(ra+1)) );
}
void diehard(int* ra, Distribution* D =0) {
poissonL2Norm(D[0], ra);
}
int main(void) { // Thanks, laserlight
Distribution* D = new Distribution[12];
int* ra;
try {
ra = new int[10000000];
} catch (bad_alloc) { // Handling not mandatory, but safe
cout << "Memory exhausted\n";
return EXIT_FAILURE;
}
long int count = 0;
seedRNG();
cout << "start: " << ra << '\n';
while(count < 10000000) {
ra[count++] = rand();
if(count % 1000000 == 0) cout << count << " values so far.\n";
}
diehard(ra, D);
delete[] ra;
delete[] D;
}
This program goes up in flames at runtime because of the way I "fill" the distribution. I just want to add one number at a time to D.dx, but I'm having trouble doing this. Any ideas? This is my first 1000-liner in C++, and it looks like I'll be 100 by the time it works completely : (
Also: Emacs' syntax highlighter for C++ is only indenting two deep. How do you tell it to go four deep? I'm so, so lost here : (