Why the following printf of the buffer in the readWav() causes segmentation fault just after printing the first row to the screen? Are there any issues with the use of pointer in printf("%d\t %f\n", i, *buffer[i]);?

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

    ret = readWav(argv[1], &nSamples, &sRates, &datas);
    if (ret != 0) {
        printf("Error\n");
        return 1;
    }

    ------
    -----

}

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

    -----
    ----
   for (i=0; i < sndInfo.frames ; i++) { 
         printf("%d\t %f\n", i, *buffer[i]); 
   } 
   // Are there any issues with the use of pointer?

    sf_close(sndFile);
    return(0);

}

You create a pointer, named datas. You don't set it to point at anything, so it's pointing at some random memory somewhere.

You then pass the address of that pointer to your readwav function; a pointer to a float-pointer. The function readwav calls this buffer and treats it as an array of float pointers. I can't see you doing anything with buffer so I have to assume you're doing nothing with it.

The first member of the array, buffer[0] will be your pointer datas, and you happily dereference that. You never set it to point at anything, so it's pointing at some random memory somewhere. Basically, you're reading memory that isn't yours to read from and that's a good way to get a segFault.

The very next element in the array buffer, since it isn't actually an array, will just be whatever happens to be in that piece of memory. Treating random memory as a pointer is also a bad idea.

Edited 1 Year Ago by Moschops

Actually in readWave() there is an operation to assign values to *buffer.

And buffer was able to correctly passed to main() and I was able to check values in main with datas[i]

How do I do this in readWav() - What is wrong with *buffer[i]) - in other words, if datas[i] refers to actual values in main() what would that be in readWav() in terms of buffer?

Edited 1 Year Ago by uws101

So, you are saying your code is correct? Yet it dumps core. You are suffering from a severe case of near-sightedness. Step back a bit and look at your code again.

This article has been dead for over six months. Start a new discussion instead.