c - App crashes though I can't understand the reason -
the input file in.wav
. have read chunks (succeeded) , read samples normalize audio file...
the problem crashes while trying fing max
, min
values of .wav file's samples. find minimum value , maximum 1 in array, crashes... tell me wrong, please.
here code:
#include <stdio.h> #include <stdlib.h> #include "main.h" #define hdr_size 64 typedef struct fmt { char subchunk1id[4]; int subchunk1size; short int audioformat; short int numchannels; int samplerate; int byterate; short int blockalign; short int bitspersample; } fmt; typedef struct data { char subchunk2id[4]; int subchunk2size; int data[441000]; } data; typedef struct header { char chunkid[4]; int chunksize; char format[4]; fmt s1; data s2; } header; int main() { file *input = fopen( "in.wav", "rb"); /// namein if(input == null) { printf("unable open wave file (input)\n"); exit(exit_failure); } file *output = fopen( "out.wav", "wb"); /// nameout header hdr; fread(&hdr, sizeof(char), hdr_size, input); /* note: chunks has been copied successfully. */ /*###############################*/ /*##### update (char *ptr;) #####*/ /*###############################*/ char *ptr; // 'int' written here instead of 'char'. that's stupid mistake... long n = hdr.s2.subchunk2size; /// copying samples... ptr = malloc(sizeof(hdr.s2.subchunk2size)); while ( n-- != 0 ) { fread(&ptr, 1, 1, input); // continues reading after least 'stop' place. } // being told here (on "stack") so... n = hdr.s2.subchunk2size; // resetting 'n'. int min = ptr[0], max = ptr[0], i; /* problem here: */ ( = 0; < n; i++ ) { if ( ptr[i] < min ) // if next elements less previous, swap them. min = ptr[i]; if ( ptr[i] > max ) // if next elements bigger previous, swap them. max = ptr[i]; } printf("> > >%d__%d\n", min, max); // displaying of 'min' , 'max'. fclose(input); fclose(output); return 0; }
update:
eureka! because of 8-bits per sample! must manipulate them ( samples ) type of char. (see "### update ###"-comment in code)
this code:
/// copying samples... ptr = malloc(sizeof(hdr.s2.subchunk2size)); while ( n-- != 0 ) { fread(&ptr, 1, 1, input); // continues reading after least 'stop' place. } // being told here (on "stack") so...
overwrites first byte of ptr
variable n
times. corrupts ptr
's value. if fixed read allocated buffer instead (by removing &
), rewriting first byte of allocated memory.
what intended was:
fread(ptr, 1, n, input);
notice while
loop not needed. but, guess on part regarding true intentions.
Comments
Post a Comment