Answer the question
In order to leave comments, you need to log in
Crash when deleting dynamic array?
When I delete - an exception.
Why? explain in as much detail as possible.
The code:
Data parseAnswerFromCOM(const char* source)
{
Data data = { };
char *s = new char[strlen(source) + 1];
char *next_token1 = NULL;
strcpy_s(s, strlen(s), source);
char *p = strtok_s(s, ";", &next_token1);
int tmpCounter = 0;
while (p != NULL)
{
cout << p << endl;
p = strtok_s(NULL, ";", &next_token1);
}
delete[] s;
return data;
}
Answer the question
In order to leave comments, you need to log in
char *s = new char[strlen(source) + 1]; ... strcpy_s(s, strlen(s), source);
strlen(s)
-- generally beyond good and evil and returns a random number, by and large. Because s is a newly allocated uninitialized array. strcpy_s
is completely meaningless and wrong. Pointless, because you just allocated as much memory as there is data in the row. strcpy_s makes sense if the buffer you're copying to is a fixed-length array. Incorrect, because even if you meant strlen(source)
, and not strlen(s)
, you had to pass strlen(source) + 1
, so that there is where to copy the 0-terminator. Among other things, strcpy_s also returns an error code, which makes sense to check. memcpy(s, source, strlen(source) + 1);
or even throw it out s = new char [...]; strcpy_s ... delete [] s;
and replace it with s = strdup(source); ... free(s);
strcpy_s(s, strlen(source) + 1, source);
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question