当我在函数内打印第一个值后尝试 printf 时出现 C 分段错误

C segmentation fault when I try to printf just after printing the first value inside function

当我尝试在 readWav() 函数中的 *buffer[i] 上使用 printf 时,出现 分段错误 buffer 能够正确传递给 main() 并且我能够使用 datas[i] 检查 main 中的值。我只是简单地复制了 main() 中的 printf 并且必须将 datas[i] 替换为 *buffer[i] 然后它编译正常。它打印 readWav() 中的第一个值,然后 SegFault 发生。

我如何在 readWav() 中执行此操作 - *buffer[i]) 有什么问题 - 换句话说,如果 datas[i] 指的是 main() 中的实际值那会是什么在 readWav()buffer?

更新: main()datas 传递给其他尚待添加的功能。这就是为什么我尝试在 readWav() 中打印它,认为它在将值传递给其他函数方面非常相似 - 如果我错了请纠正我?

#include <stdio.h>
#include "sndfile.h"

int readWav(const char *const fname, long *numFrames, int *sRate, float **buffer);

int main(int argc, char *argv[])
{
    int   sRates, sRatem, ret;
    long  nSamples = 0, nSamplem;
    float *datas, *datam;

    printf("Read Test\n");
    if (argc != 3) {
        fprintf(stderr, "Expecting two wav file as argument\n");
        return 1;
    }

    ret = readWav(argv[1], &nSamples, &sRates, &datas);
    if (ret != 0) {
        printf("Error\n");
        return 1;
    }
    // Output Info
    printf("Read %ld frames from %s, Sample rate: %d, Length: %fs\n",
        nSamples, argv[1], sRates, (float)nSamples/sRates);

    for (i=0; i < nSamples ; i++) {
        printf("%d\t %f\n", i, datas[i]);
    }

    free(datas);

    return 0;
//Cleanup etc:
}

int readWav(const char *const fname, long *numFrames, int *sRate, float **buffer)
{
    // Open sound file
    SF_INFO sndInfo;

    if ((sRate == NULL) || (numFrames == NULL) || (buffer == NULL)) {
        fprintf(stderr, "Invalid arguments passed to readWav()\n");
        return 1;
    }

    SNDFILE *sndFile = sf_open(fname, SFM_READ, &sndInfo);
    if (sndFile == NULL) {
        fprintf(stderr, "Error reading source file '%s': %s\n", fname, sf_strerror(sndFile));
        return 1;
    }

    // Allocate memory
    *buffer = malloc(sndInfo.frames * sndInfo.channels * sizeof(float));
    if (*buffer == NULL) {
        fprintf(stderr, "Could not allocate memory for file\n");
        sf_close(sndFile);

        return 1;
    }

    *sRate = sndInfo.samplerate;
    // Load data
    *numFrames = sf_readf_float(sndFile, *buffer, sndInfo.frames);
    // Check correct number of samples loaded
    if (*numFrames != sndInfo.frames) {
        fprintf(stderr, "Did not read enough frames for source\n");
        sf_close(sndFile);
        free(*buffer);
    }
    else {
        printf("Successfully read file\n");
        *numFrames = sndInfo.frames;
    }
    // Output Info
    printf("Read %ld frames from %s, Sample rate: %d, Length: %fs\n",
        *numFrames, fname, *sRate, (float)*numFrames/sndInfo.samplerate);

    for (i=0; i < sndInfo.frames ; i++) {
        printf("%d\t %f\n", i, *buffer[i]);
    }

    sf_close(sndFile);
    return(0);
}

您正在访问数组索引 BEFORE 解除对指针的引用。

您本来想做 (*buffer)[i],但做了 *(buffer[i]) 而不是 (请注意为了清楚起见我是如何添加括号的).

下次,请记住 * 的优先级低于 []