Search code examples
c++arraysfunctionpointersdynamic-memory-allocation

Error when writing from file into pointer of string array (read access violation)? CPP


For a problem, I have to use dynamic allocation and functions (using pointer variables only) to read the names from the .txt file and sort the names in lexical order. However, I cannot even get the read function to work properly. This is what it wrote:

void readNames(std::string* a[])
{
    std::ifstream fin; 
    fin.open("names.txt");
    for (int i = 0; i < 7; ++i)
    {
        fin >> *(a[i]); 
        std::cout << *a[i];
    }
}

This is how I called it in main:

std::string* names;
names = new std::string[7];
readNames(&names);

However, when I run this I get the error:

Exception thrown: read access violation. this was 0xCCCCCCCC.

And this function is displayed(not sure if this helps):

 void _Check_offset(const size_type _Off) const { // checks whether _Off is in the bounds of [0, size()]
        if (_Mysize < _Off) {
            _Xran();
        }
    }

If anyone can help me with this I would relly appreciate it, thank you!


Solution

  • To elaborate on WhozCraig's comment, let us assume the following:

    • names resides on the stack, so we give it address 0x7f001000.
    • The array of strings you allocates resides on the heap, so we give it address 0x1000
    • You assigned that address to names, so address 0x7f001000 contains the value 0x1000.

    Inside readNames, a is the address of names, so the expression *(a[i]) can be rewritten as:

    *(*(&names + i))
    

    For i=0, this works out. You basically dereference a once to get the start of the array, and then again to get a reference to the first allocated std::string.

    For any other i, you access data on the stack (0x7f001000 + i) and then dereference that value as a pointer to a std::string.

    By writing (*a)[i] you get the following calculation instead:

    *(*(&names) + i) 
    

    which is

    *(names + i)
    

    , or

    names[i]