tl300
tl300

Reputation: 31

memory allocation error while converting string to char*

I need some help figuring out a memory allocation error. I keep getting this error:

Error: Memory could not be allocated.

...when fList is large in the following code:

for (unsigned int ii=0; ii<fList.size(); ii++) {

    char *fName = new char[fList[ii].length() + 1];
    strcpy(fName, fList[ii].c_str());
    err = xInitFile(fName, ii+1);
    if(err != 0) {
        cout << "FOOBAR" << endl;
    }               
    delete[] fName;
}

fList is a std::vector<std::string>.

The function xInitFile is a C shared library function with the following prototype:

int xInitFile(char *fName, int fHandle)

If fList is small, then everything runs fine. I'm pretty sure the problem lies in how I'm converting the string to a char *, but I can't figure out how to fix it. As far as I can tell, fName is always deleted, so it doesn't appear to be a memory leak. My memory usage doesn't spike while running the code either.

EDIT:

Commenting out err = xInitFile(fName, ii+1); eliminates the error. That means the allocation error is occurring in the xInitFile, right? I didn't think to try this earlier, because I thought the problem was in my code (b/c I'm new to C++).

Upvotes: 1

Views: 276

Answers (1)

enhzflep
enhzflep

Reputation: 13109

It's probably frowned upon for one reason or another, but I'd be inclined to instead try strdup.

char *fName = strdup( fList[ii].c_str() );

paired with

free(fName);

Upvotes: 1

Related Questions