如何正确地将内存分配给动态char数组

时间:2013-11-17 03:34:33

标签: c++ arrays c-strings

我尝试使用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?

1 个答案:

答案 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;
}