I cant manage to sum a few vectors. Values are gigantic and only iterates about 800 times until theres no more memory. I guess I am not handling pointers correctly, but I cant work it out. anybody see anything strange?
Code:
float *amp, *sum_amp;
SOME SKIPPED CODE
// memory allocations
sum_amp = (float *)calloc(nx*ny, sizeof(float));
if (!sum_amp) perror("Insufficient memory!");
amp = (float *)calloc(nx*ny, sizeof(float));
if (!amp) perror("Insufficient memory!");
// for each line
printf("Creating mean amplitude from files...\n"); //info
for (ii=0;ii<kk;ii++)
{
fgets(line,sizeof(line),fp);
// remove newline
if ((p = strchr(line, '\n')) != NULL) *p = '\0';
//read headerfile
read_header(line);
// create amplitude filename to open
strcpy(amp_filename, path);
strcat(amp_filename, "amp_");
strcat(amp_filename, filename);
strcat(amp_filename, ".bin");
//try fopen amp_in
if (!(amp_in = fopen(amp_filename, "rb")))
{
printf("\nAmplitude file not found!\n");
exit(0);
}
// read data
fread( (float *)amp, sizeof(float), nx*ny, amp_in);
// accumulate amplitudes
for (i=0;i<nx*ny;i++)
{
sum_amp[i] += amp[i];
printf("i = %d, sum_amp = %f\n",i, sum_amp[i]); //trace
}
fclose(amp_in);
}//for
fclose(fp);
If I put the calloc allocations inside the for loop, it seems to work (numbers dont get gigantic at least) but it doesnt solve my problem since I want sum up multiple vectors, so I dont want to reset sum_amp to 0 next iteration.