int subroutine (char *input, float *buffer)
{
    *buffer = malloc(...)
    buffer is calculated from input
}

or

flot subroutine (char *input)
{
    *output = malloc(...)
    buffer is calculated from input
    return(buffer);
}

int main(int argc, char *argv[])
{
    float *data;
    subroutine(argv[] ...)
    ...
    free(data)
}

1) which subroutine is recommended?
2) If I malloc-ed the buffer in subroutine, where do I have to free it?
3) Is freeing data in the main sufficient?
4) Do I have to free the buffer in subroutine?

Recommended Answers

All 2 Replies

Please use real C code here. We need to see exactly what you are trying to do.

My question is asking how I can pass the file name (which I can do) to a subroutine and then subroutine opens it, reads it and return the array values (pointer ?) - in addition, freeing the malloc space when and where?

I have trouble returning the array and in freeing the memory.

Code: I want to separate the code below - move the open/reading part into a subroutine as I have multiple files to open/read - so the main will just work on read values.

Line 13 to around line 48 to be moved to subroutine.

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

int main(int argc, char *argv[])
{
    printf("Wav Read Test\n");
    if (argc != 2) {
        fprintf(stderr, "Expecting wav file as argument\n");
        return 1;
    }

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

    // Check format - 16bit PCM
    if (sndInfo.format != (SF_FORMAT_WAV | SF_FORMAT_PCM_16)) {
        fprintf(stderr, "Input should be 16bit Wav\n");
        sf_close(sndFile);
        return 1;
    }

    // Check channels - mono
    if (sndInfo.channels != 1) {
        fprintf(stderr, "Wrong number of channels\n");
        sf_close(sndFile);
        return 1;
    }

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

    // Load data
    long 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);
        return 1;
    }

    // Output Info
    printf("Read %ld frames from %s, Sample rate: %d, Length: %fs\n",
        numFrames, argv[1], sndInfo.samplerate, (float)numFrames/sndInfo.samplerate);

    sf_close(sndFile);
    free(buffer);

    return 0;
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.