应用程序在查找数组中的元素时崩溃

时间:2013-05-09 20:02:18

标签: c pointers malloc binaryfiles

输入文件为in.wav。我必须读取块(成功)并读取样本以规范化音频文件...

问题是它在尝试查找.wav文件样本的maxmin值时崩溃了。 它只会找到数组中的最小值和最大值,但崩溃 ......

请告诉我有什么问题。我认为没有理由这种行为。

以下是代码:

#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 to 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;

    /* THE PROBLEM IS HERE: */
    for ( i = 0; i <= n; i++ )  // Finding 'max' and 'min'.
        {
            if ( ptr[i] < min )    
                min = ptr[i];
            if ( ptr[i] > max ) 
                max = ptr[i];
    }

    printf("> > >%d__%d\n", min, max);    // Displaying of 'min' and 'max'.

    fclose(input);
    fclose(output);

    return 0;
}

为什么它本身如此奇怪?

2 个答案:

答案 0 :(得分:6)

问题出在(至少)

ptr = malloc(sizeof(n));

因为 sizeof(n)是4 ,sizeof(n)等于sizeof(long)。你刚刚为ptr分配了4个字节。

您的问题的解决方案如下:

ptr = malloc(n); 
/* It will allocate the size of 'n' (27164102 bytes),
   but not the data type size (4 bytes). */

答案 1 :(得分:4)

数组的索引从零到n-1,但在下面的代码中:

for ( i = 0; i <= n; i++ )

您正尝试从零读到n