我尝试使用malloc和new但在任何一种情况下我最终得到的数组大小为24.发生了什么事?
//I want to copy the last nine characters to a new string
//the function is basically for copying last x number of characters to a new string.
int main ()
{
char str[] = "1234567890";
int offset=1;
int j=offset;
int len=strlen(str);
cout<<len-offset<<endl;
char str[] = "1234567890";
char* s=new char[9];
for(int i=0;j<len;i++){
s[i]=str[j];
j++;
}
cout<<strlen(s);
return 0;
}
现在我猜测分配的内存以字节为单位。但后来我分配9个字节,为什么它显示为24?
答案 0 :(得分:1)
我在下面评论了您的代码,以显示正在发生的事情。你有一个缓冲区溢出的情况,因为你覆盖的内存比你为s
分配的内存多。这会导致未定义的行为。如果您不熟悉缓冲区溢出,请务必查看this post。你将是一个更好的程序员来阅读它。
//I want to copy the last nine characters to a new string
//the function is basically for copying last x number of characters to a new string.
int main ()
{
char str[] = "1234567890";
int offset=1;
int j=offset;
int len=strlen(str); // len == 10
cout<<len-offset<<endl;
char str[] = "1234567890";
char* s=new char[9]; // s has room for 9 bytes
for(int i=0;j<len;i++){ // len == 10
s[i]=str[j];
j++;
}
// You've now written past the end of the memory allocated for s.
// Welcome to undefined behavior land
cout<<strlen(s);
return 0;
}