#include <iostream>
#include <string>
using namespace std;
char* tach(const char* s)
{
char* str = new char;
int i;
for (i = 0; s[i] != NULL; i++)
if (s[i] != ' ')
str[i] = s[i];
else
break;
str[i] = NULL;
return str;
}
int main()
{
char* s;
s = tach("viet nam");
cout << s << endl;
delete s;
return 0;
}
Đề bài: Viết chương trình tách 1 từ ra khỏi 1 xâu kí tự
Mọi người có thể cho em hỏi khi em code như ở trên thì trên VS nó báo lỗi Debug Error! (HEAP CORRUPTION DETECTED…) ạ. Còn khi em thử trên codeblocks thì vẫn chạy bình thường
Em thử sửa lại thành như này
#include <iostream>
#include <string>
using namespace std;
char* tach(const char* s)
{
char* str = new char[strlen(s) + 1];
int i;
for (i = 0; s[i] != NULL; i++)
if (s[i] != ' ')
str[i] = s[i];
else
break;
str[i] = NULL;
return str;
}
int main()
{
char* s;
s = tach("viet nam");
cout << s << endl;
delete[] s;
return 0;
}
thì trên VS lại chạy được bình thường ạ
Ai có thể giải thích giúp em với được không ạ? Em cảm ơn!