access memory violation

Hello Everyone so i am trying to copy the contents of a list into a char array but i get an access memory violation error when using memcpy, my code i use is below:

[code]
int currIteration = 0;
char ** pwdAry;
pwdAry = new char *[numberOfPwd];

for (int a = 0; a < 4; a++) {
pwdAry[a] = new char[1024];
}
for (int i = 0; i < List.size(); i++)
{
string tmp = List.front();
char * val;
val = new char[1024];
const char* cstr;

cstr = tmp.c_str();
memset(pwdAry[currIteration], 0, 1024);
memcpy(pwdAry[currIteration], cstr, (strlen(cstr)));
val[tmp.size()] = '\0';

currIteration++;


List.pop_front();

}
[code]

Does anyone know why i am getting this error? Thank you.
Ah, I've just noticed that I have the size of the 2nd dimension of the char array only set to size of 4 not the size of the list :)

[code]
int currIteration = 0;
char ** pwdAry;
pwdAry = new char *[numberOfPwd];

for (int a = 0; a < List.size(); a++) {
pwdAry[a] = new char[1024];
}
for (int i = 0; i < List.size(); i++)
{
string tmp = List.front();
char * val;
val = new char[1024];
const char* cstr;

cstr = tmp.c_str();
memset(pwdAry[currIteration], 0, 1024);
memcpy(pwdAry[currIteration], cstr, (strlen(cstr)));
val[tmp.size()] = '\0';

currIteration++;


List.pop_front();

}
[code]

Shall I leave the solution up for people?
That's a lovely memory leak you have there.
@shorty5161: Presumably you can see for yourself that you've made a mistake with your code tags?
Last edited on
Fixing all the errors shortens that code considerably:

1
2
    std::vector<std::string> pwdAry(List.begin(), List.end());
    List.clear();


it could also be optimized to avoid copying any characters:

1
2
3
4
    std::vector<std::string> pwdAry(
        std::make_move_iterator(List.begin()),
        std::make_move_iterator(List.end()));
    List.clear();


Last edited on
Topic archived. No new replies allowed.