使用malloc保留连续块

reserving continuous block using malloc

本文关键字:连续 保留 malloc 使用      更新时间:2023-10-16

我想更多地了解malloc(),需要帮助澄清输出。我想保留10字节的内存,并且能够单独访问它们,但它们必须在一个块中。下面是代码:

#include<iostream>
using namespace std;
#include<stdio.h>
#include<stdlib.h>
int main()
{
    char neededbytes = 10;
    char *p;
    p = (char *)malloc(neededbytes * sizeof(char));
    if(p==NULL)                     
    {
        cout<<"Error! memory not allocated.";
        exit(0);
    }
    else
    {
        for (int i = 0; i < neededbytes; i++)
        {
            p[i] = 0;
        }
        for (int i = 0; i < neededbytes; i++)
        {
            cout<<"Address at index " << i << " is ";
            cout<<&p+i<<endl;
        }
    }
    free(p);
}

程序的输出显示所有地址间隔为8字节。它们不应该只有一个字节的距离吗?是否有一种方法可以让我知道char在我的体系结构上是否消耗了8字节?

&p+i(&p)+(i)相同,由于p具有char*类型,因此&p具有char**类型。因此,添加i实际上会为&p表示的地址添加i * sizeof(char *)字节。

你想要的是p + i,它将i * sizeof(char)字节添加到p中存储的地址。换句话说,当您使用malloc()时,您已经有一个指向连续数据的指针。当然,这是c++,所以char *通常由std::coutstd::cerrstd::ostream类专门处理。你需要做像static_cast<void *>(p + i)这样的东西,而不仅仅是p + i,就像你在c中使用的那样。

正如其他人所说,你应该尽可能避免在c++中使用malloc()free();c++有new[]delete[]运算符,

cout<<&p+i<<endl;应该是cout<<static_cast<void*>(p+i)<<endl;

这是因为您正在使用操作符的地址,在这种情况下,偏移量将是i * sizeof(char *),在您的系统上显然是8 * i字节。

试试这个

#include <iostream>
#include <stdio.h>
#include <stdlib.h>
using namespace std;
int main()
{
    char neededbytes = 10;
    char *p;
    p = static_cast<char *>(malloc(neededbytes));
    if (p == NULL)
    {
        cout << "Error! memory not allocated.";
        exit(-1);
    }
    for (int i = 0; i < neededbytes; i++)
        p[i] = 0;
    for (int i = 0; i < neededbytes; i++)
    {
        cout << "Address at index " << i << " is ";
        cout << static_cast<void *>(p + i) << endl;
    }
    free(p);
}

你可以在你的编译器输出设置中查看char的字节对齐,但我打赌char总是1字节。尝试像这样的一些变化(我认为你正在访问错误的数组元素在&p+i):

int main()
{
    int neededbytes = 10;
    char *p=NULL;
    p = malloc(neededbytes * sizeof(char));
   if(p==NULL)                     
   {
      cout<<"Error! memory not allocated.";
      exit(0);
   }
else
{
    for (int i = 0; i < neededbytes; i++)
    {
        p[i] = 0;
    }
    for (int i = 0; i < neededbytes; i++)
    {
        cout<<"Address at index " << i << " is ";
        // Dave cout<<p+i<<endl;
        cout<<&(p+i)<<endl;
    }
}
free(p);
}

注意:Dave分享了p+i的正确语法。谢谢你戴夫

cout<<&p+i<<endl;更改为cout<<static_cast<void*>(p+i)<<endl;

这是一个讨论GNU系统上内存对齐的站点。它将始终以8(64位系统为16)字节对齐。这里列出了一些libc (stdlib.h)函数可以强制对齐。

http://www.gnu.org/software/libc/manual/html_node/Aligned-Memory-Blocks.html