c - App crashes while finding elements in array -
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, it crashes...
tell me wrong, please. see no reason of such kind of behaviour.
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. */ char *ptr; long n = hdr.s2.subchunk2size; /// copying samples... ptr = malloc(sizeof(n)); fread( ptr, 1, n, input ); int min = ptr[0], max = ptr[0], i; /* problem here: */ ( = 0; <= n; i++ ) // finding 'max' , 'min'. { if ( ptr[i] < min ) min = ptr[i]; if ( ptr[i] > max ) max = ptr[i]; } printf("> > >%d__%d\n", min, max); // displaying of 'min' , 'max'. fclose(input); fclose(output); return 0; }
why behaves strange?
problem in (at least)
ptr = malloc(sizeof(n));
because sizeof(n) 4, sizeof(n) equals sizeof(long). allocated 4 bytes ptr.
the solution of problem following:
ptr = malloc(n); /* allocate size of 'n' (27164102 bytes), not data type size (4 bytes). */
Comments
Post a Comment