0

How do I fill the buffer which is void *?

The buffer should be filled with 2 bytes which is int16_t.

I have a function:

/**
 * @brief 
 * Should fill up the buffer;
 * @param mics 
 * @param bufferIn 
 * @return size_t 
 */ 
size_t fillBufferIn(FILE *in, void *buffer, size_t bytes) //1920 byte
{ 
  size_t Nread;
  /**
   * @brief 
   * Should return a buffer with float[][] so that it can read and write
   * Each time it read sizeof of two int16_t which are the left channel and right channel
   * 
   */
  buffer = (void *)calloc(480,2*sizeof(int16_t));
  Nread = fread(buffer, 2*sizeof(int16_t), 480, in);

  return Nread;
}

In main I call it like this:

 while(!feof(infile))
  {
    Nread = fillBufferIn(infile, bufferIn, bytes);

    int16_t *bufferInCasted = (int16_t *)bufferIn;

    printf("%ld bytes read\n",Nread * 2 * sizeof(int16_t));

    for(int i = 0 ; i < 480 ; i++)
    {
      printf("I:  %d\t", i);
      printf("Left Sample %d\t", bufferInCasted[i]);
      printf("Right Sample %d\n\n", bufferInCasted[1+i*2]);
    }

I get seg.fault, Why ? Isn't that calloc call available outside of the scope of the function.

Gent Binaku
  • 55
  • 11
  • 1
    See [**Why is “while ( !feof (file) )” always wrong?**](https://stackoverflow.com/questions/5431941/why-is-while-feof-file-always-wrong) – Andrew Henle Jun 18 '20 at 14:37

1 Answers1

2

buffer is a local variable in fillBufferIn. Changes to it won't be reflected in the calling program.

You need to pass a pointer to the variable you want to change so you can modify it. So change your function to:

size_t fillBufferIn(FILE *in, void **buffer, size_t bytes) //1920 byte
{ 
  size_t Nread;
  /**
   * @brief 
   * Should return a buffer with float[][] so that it can read and write
   * Each time it read sizeof of two int16_t which are the left channel and right channel
   * 
   */
  *buffer = calloc(480,2*sizeof(int16_t));
  Nread = fread(*buffer, 2*sizeof(int16_t), 480, in);

  return Nread;
}

And call it like this:

Nread = fillBufferIn(infile, &bufferIn, bytes);
dbush
  • 205,898
  • 23
  • 218
  • 273