标签: dynamic-allocation

如何使用户无法删除动态数组呢?

在编写响应时,我编写了一些代码来挑战我对const指针如何工作的假设.我假设删除函数无法删除const指针,但正如您将从下面的代码中看到的那样,情况并非如此:

#include <new>
#include <string.h>

class TestA
{
    private:
        char *Array;
    public:
        TestA(){Array = NULL; Array = new (std::nothrow) char[20]; if(Array != NULL){ strcpy(Array,"Input data"); } }
        ~TestA(){if(Array != NULL){ delete [] Array;} }

        char * const GetArray(){ return Array; }
};

int main()
{
    TestA Temp;
    printf("%s\n",Temp.GetArray());
    Temp.GetArray()[0] = ' '; //You can still modify the chars in the array, user has access
    Temp.GetArray()[1] = ' '; 
    printf("%s\n",Temp.GetArray());
    //Temp.GetArray() = NULL //This doesn't work

    delete [] Temp.GetArray(); //This works?! …
Run Code Online (Sandbox Code Playgroud)

c++ pointers dynamic-allocation

2
推荐指数
2
解决办法
199
查看次数

智能指针诞生之前

在智能指针(能够获得动态区域中的资源所有权并在使用后释放它们)出现之前,我想知道当作为参数传递给占用资源指针的函数时,动态创建的对象的簿记是如何执行的.

通过簿记,我的意思是,如果有一个"新",那么稍后在它之后应该有一个"删除".否则,程序将遭受内存泄漏.

这是一个例子,B是一个类,void a_function(B*)是第三方库函数:

void main() {

  B* b = new B(); // line1

  a_function(b);  // line2

  ???             // line3
}
Run Code Online (Sandbox Code Playgroud)

我在第3行做什么?我是否认为第三方功能已经解除了内存的分配?如果没有,我认为它有,那么我的程序会遇到内存泄漏.但是,如果它取消分配b占用的内存而且我也在main()中执行它以便安全,那么b实际上最终会被释放两次!由于双重免费错误,我的程序会崩溃!

c++ dynamic-allocation

2
推荐指数
1
解决办法
240
查看次数

当按值填充std :: vector时,会动态分配对象指针吗?

可能重复:
为什么使用'new'导致内存泄漏?

我对STL很新,而且我已经读过,通常保持对象的向量而不是对象的指针向量是一种好习惯.为了遵守这个信条,我遇到了以下情况:

//Approach A
//dynamically allocates mem for DD_DungeonRoom object, returns a pointer to the block.
//then, presumably, copy-constructs the de-referenced DD_DungeonRoom as a 
//disparate DD_DungeonRoom object to be stored at the tail of the vector
//Probably causes memory leak due to the dynamically allocated mem block not being
//caught and explicitly deleted
mvLayoutArray.push_back(*(new DD_DungeonRoom()));

//Approach B
//same as A, but implemented in such a way that the dynamically allocated mem block
//tempRoom can be deleted after it is …
Run Code Online (Sandbox Code Playgroud)

c++ pointers memory-leaks vector dynamic-allocation

2
推荐指数
1
解决办法
860
查看次数

为什么我的动态分配的结构数组不在C中工作?

我一直在尝试创建一个动态分配的struct类型数组,label并且一直在失败.在我的.h文件中,我有:

    typedef struct _label {
            char name[256];
            char type[256];
            int address;
} label;
Run Code Online (Sandbox Code Playgroud)

在我的.c文件中,我在顶部有这个:

    label* allLabels = (label*) malloc(sizeof(label) * 10); // line 10
    int arrayIndex = 0;
Run Code Online (Sandbox Code Playgroud)

最后,我在同一个.c文件中有一个函数,用于将这些结构对象添加到数组中,供文件中的其他方法使用:

    void addLabel(char line[], char type[], int addr) {
            label database;
            database.name = line; // line 805
            database.type = type; // line 806
            database.address = addr;
            allLabels[arrayIndex] = database;
            arrayIndex++;
        }
Run Code Online (Sandbox Code Playgroud)

基本上我只想拥有一组可访问的标签.有人能帮助我理解我做错了什么吗?

我收到这些错误,我也没有忘记任何必要的#include语句:

formatBuilder.c:10:3: error: initializer element is not constant
formatBuilder.c: In function 'addLabel':
formatBuilder.c:805:18: error: incompatible types when assigning …
Run Code Online (Sandbox Code Playgroud)

c arrays struct dynamic-allocation

2
推荐指数
1
解决办法
864
查看次数

malloc有什么优势?

为某些数据分配内存有什么好处.相反,我们可以使用它们的数组.

喜欢

 int *lis;
 lis = (int*) malloc ( sizeof( int ) * n );

 /* Initialize LIS values for all indexes */
 for ( i = 0; i < n; i++ )
 lis[i] = 1;
Run Code Online (Sandbox Code Playgroud)

我们可以使用普通的数组.

好吧,我不明白malloc是如何工作的,实际上是做什么的.所以解释它们对我来说会更有益.

假设我们sizeof(int) * n只n用上面的代码替换然后尝试存储整数值,我可能面临哪些问题?有没有办法直接从内存分配空间打印存储在变量中的值,例如这里是lis?

c++ arrays malloc dynamic-allocation variable-length-array

2
推荐指数
1
解决办法
2592
查看次数

试图在矢量类中创建复制功能

我正在努力实现一个矢量类,但无法弄清楚如何编写一个函数来将一个矢量复制到另一个矢量.

template <class T> class Vec {

public:
//TYPEDEFS
    typedef T* iterator;
    typedef const T* const_iterator;
    typedef unsigned int size_type;

//CONSTRUCTOS, ASSIGNMENT OPERATOR, & DESTRUCTOR
    Vec() {this->create(); }
    Vec(size_type n, const T& t = T()) { this->create(n, t); }
    Vec(const Vec& v) { copy(v); }
    Vec& operator=(const Vec& v);
    ~Vec() { delete [] m_data; }

//MEMBER FUNCTIONS AND OTHER OPERATORS
    T& operator[] (size_type i) { return m_data[i]; }
    const T& operator[] (size_type i) const { return m_data[i]; }
    void push_back …
Run Code Online (Sandbox Code Playgroud)

c++ vector pass-by-reference dynamic-allocation

2
推荐指数
1
解决办法
125
查看次数

为什么Rust的排序方法会分配内存?

像sort_byon std::slice::MutableSliceAllocating或sort_byon 这样的方法collections::vec::Vec被记录为"分配大约2*n,其中n是长度".我不认为好的C++ std::sort实现(在堆上)分配,但它们实现了相同的O(n log n)复杂性.虽然,与C++ std :: sort不同,Rust排序方法是稳定的.

为什么Rust排序方法分配?对我来说,它不符合这里宣传的"零成本抽象"法案.

sorting dynamic-allocation rust

2
推荐指数
2
解决办法
791
查看次数

添加值时Fortran阵列会自动增长

有没有现成的方法来模拟Fortran中不断增长的数组?就像C++中的vector一样.当我在互联网上没有找到关于这个主题的任何内容时,我感到非常惊讶.

作为一个动机示例,假设我计算一些递归关系,我想存储我得到的所有中间数.我的停止标准是相邻结果之间的差异,所以我事先不知道应该为此分配多少内存.

fortran vector dynamic-allocation

2
推荐指数
1
解决办法
687
查看次数

动态分配指针数组及其替代方案

使用new int分配数组的标准方法是:

 int* arr = new int[50];
Run Code Online (Sandbox Code Playgroud)

在以这种方式声明它的同时,将存在连续的内存分配,并且变量堆栈中将存在单个数组变量.

如果我想以50个不同的指针变量的形式声明它,以便每个指针具有不同的内存地址,而不一定是连续的,最明显的方法是这样:

int * arr[50];
Run Code Online (Sandbox Code Playgroud)

但是以这种方式分配内存的命令/代码(即通过new int)以及以各种方式声明的缺点或优点是什么.

c++ arrays pointers memory-management dynamic-allocation

2
推荐指数
1
解决办法
1166
查看次数

Valgrind显示分配的内存比实际多

我在C中编写了一些简单的代码来测试一些内存分配和指针:

#include <stdlib.h>
#include <stdio.h>


int *randomAlloc(int n) {
    int *address = NULL, i = 0;

    address = malloc (n * sizeof(int));
    for (i = 0; i < n ; i++){
        *(address + i) = i ;
    }
    return address;

}

int main(int argc, char* argv[] ) {

    int *address;
    int n;
    printf("Type vector size: ");
    scanf("%d", &n);
    address = randomAlloc(n);

    free(address);
}
Run Code Online (Sandbox Code Playgroud)

但是由于某些原因,当我输入4作为输入valgrind输出时:

==2375== Memcheck, a memory error detector
==2375== Copyright (C) 2002-2015, and GNU GPL'd, by Julian Seward …
Run Code Online (Sandbox Code Playgroud)

c malloc free valgrind dynamic-allocation

2
推荐指数
1
解决办法
777
查看次数