Troubles for PCM reading on mac

Hello,

I encounter problems on a drum plugin that read PCMFiles.
It is working on windows but not on mac.
Do somebody know if this part of code is problemaic for mac using?

void waveTable::loadSample(char *name)
{
    if (strcmp(tableName, name) != 0)
    {
        buf.clear();
        vector<float> tBuf;
        buf.swap(tBuf);
        strcpy(tableName, name);
        char pathName [4] = "PCM/";
        strcat(pathName, tableName);
        std::string filename = assetPlugin(plugin, pathName);
        buf.push_back(0);
        int len;
        const char *fname = filename.c_str();
        FILE *myfile = fopen(fname, "rb");
       // ifstream myfile (filename);
          if (myfile != NULL)
          {
            fseek(myfile, 0, SEEK_END);
            len = ftell(myfile);
            int8_t *buffer = new int8_t[len];
            fseek(myfile, 0, 0);
            fread(buffer, sizeof(int8_t), len, myfile);
            fclose(myfile);
            for (int i = 0; i < len; i++)
            {
                  buf.push_back(buffer[i]);
            }
            wasSet = true;
          }
    }
}

You have two memory stomp bugs here:

char pathName [4] = “PCM/”; strcat(pathName, tableName);

You’re creating a 4-character array, then writing a 5-byte string into it (5 because of the trailing null character). For me, Visual Studio refuses to compile it:

test.cpp(12): error C2117: ‘pathName’: array bounds overflow

and so does GCC:

test.cpp:12:21: error: initializer-string for array of chars is too long [-fpermissive] char pathName[4] = “PCM/”;

Do you not get a compiler error for that on your platform, or at least a warning?

But that aside, you then append another string into the end of that 4-character buffer, stomping off into the surrounding memory by the length of tableName. This is undefined behaviour on any platform - you’re (un)lucky it worked anywhere!

You’re writing in an odd hybrid of C and C++, and falling into C traps that C++ fixes. If you use std::string rather than character arrays, you’ll avoid problem like this.

1 Like

Sorry I ve just correct this line when posting the question because it was writed “char pathName[100] = “PCM/”;” and though it was a bit too much :slight_smile:
just change to char pathName[100] = “PCM/”; as it was originally and it should compile.
Sorry

OK I ll try with std::string. Thank you
Yes I have the bad habit to sometime use c in c++ project.