标签: dynamic-memory-allocation

与结构体一起使用时 calloc 的初始值

我正在尝试使用以下代码编写一个非常简单的哈希表:

#include <stdio.h>
#include <string.h>
#define SIZE 10

typedef struct {
    char *first_name;
    char *last_name;
} Employee;

typedef struct {
    Employee *table;
} Hashtable;

void initHashtable(Hashtable *ht) {
    ht->table = (Employee *)calloc(SIZE, sizeof(Employee));
}

int hashKey(char *key) {
    int length = strlen(key);
    return length % SIZE;
}

void put(Hashtable *ht, Employee emp, char *key) {
    int hashedKey = hashKey(key);
    ht->table[hashedKey] = emp;
}
Run Code Online (Sandbox Code Playgroud)

我可以通过执行以下操作插入元素:

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

    Employee e1;
    e1.first_name = "John";
    e1.last_name = "Doe";

    Hashtable …
Run Code Online (Sandbox Code Playgroud)

c struct heap-memory calloc dynamic-memory-allocation

0
推荐指数
1
解决办法
1546
查看次数

调用析构函数释放动态分配的内存

让我们考虑一下这段代码:

#include <iostream>
class A{
public:
        ~A() {}
};
int main(){
        A *p = new A();
        p->~A();
        return 0;
}
Run Code Online (Sandbox Code Playgroud)

我想知道所A指向的对象的内存p是否被释放或者我们必须调用delete p;

c++ destructor dynamic-memory-allocation

0
推荐指数
1
解决办法
151
查看次数

将字符串分配给 char 指针是有效的,但将整数分配给 int 指针在 C 中无效。为什么?

可以为字符指针分配任意字符串,但不能为整数指针分配整数。由于它们都是指针并包含地址。为什么在动态分配之前将 C 中的字符串分配给指针有效但整数无效。

#include<stdio.h>

int main()
{
        char *s = "sample_string"; // valid
        printf("%s\n", s);
        int *p = (int)5; // invalid
        printf("%d\n", *p);
        return 0;
}
Run Code Online (Sandbox Code Playgroud)

这给出了输出:

sample_string
Segmentation fault (core dumped)
Run Code Online (Sandbox Code Playgroud)

背后的原因是什么?虽然它们在 C++ 中都是无效的。

c pointers character dynamic-memory-allocation

0
推荐指数
1
解决办法
116
查看次数

C++ 中的 delete[] 运算符无法正常工作

请看看下面的代码::

    #include<iostream>
    using namespace std;
    
    int main()
    {
         int *ptr;
    
        ptr = new int[100000];
    
        cout<<"\n\n address = "<<ptr;

        for(long int i=0;i<100000;i++)
            *(ptr+i) = i+1;
    
        delete []ptr;
        cout<<"\n\n address = "<<ptr;

        ptr = new int[5];
        cout<<"\n\n address = "<<ptr;
        
        return 0;
    }
Run Code Online (Sandbox Code Playgroud)

输出是:

address = 0xd42490

 address = 0xd42490

 address = 0xe919d0
Run Code Online (Sandbox Code Playgroud)

为什么,在delete []ptr;它仍然指向它之前的位置之后(见第二个输出)。

c++ dynamic-memory-allocation delete-operator

0
推荐指数
1
解决办法
97
查看次数

为什么我的指针删除后仍然指向一个地址?

我正在学习 C++,但无法理解与指针相关的某些行为。

我有一个简单的自定义对象,如下所示:

class Human {
public:
       //constructor here
private:
       std::string name;
       std::string address;
}
Run Code Online (Sandbox Code Playgroud)

另一个具有指向人类指针的实例变量类型的自定义对象:

class property {
public:
       Human * ppl;//pointer to the above human object
}
Run Code Online (Sandbox Code Playgroud)

并运行这段代码:

Human * human = new Human("Mark", "address");// pointer address 0x123456 for example
Property * property = new Property();
property->ppl = human;//pass the pointer to property's instance variable 
delete human; 
human = NULL;//after deleting and setting it to NULL property.ppl still points to 0x123456
Run Code Online (Sandbox Code Playgroud)

运行上面的代码后,property下的ppl实例变量仍然指向原来的内存地址,但是里面的内容(name和address)都被清除了(现在是空字符串),我想知道为什么会这样?既然我传递了原始指针,为什么删除它并将其设置为NULL后,它仍然指向一个内存地址,但它的内容已被清除?

仅供参考:我使用 XCode 作为调试 IDE 和 C++11

c++ pointers class dynamic-memory-allocation

0
推荐指数
1
解决办法
98
查看次数

在堆上“溶解”C++ 数组是否安全?

我目前正在实现我自己的矢量容器,但遇到了一个非常有趣的问题(至少对我来说)。这可能是一个愚蠢的问题,但idk。

我的向量使用一个堆指针数组来堆分配未知类型 (T**) 的对象。我这样做是因为我希望对单个元素的指针和引用保持不变,即使在调整大小之后也是如此。

这是在构造和复制时以性能为代价的,因为我需要在堆上创建数组以及在堆上创建数组的每个对象。(堆分配比堆栈慢,对吧?)

T** arr = new *T[size]{nullptr};
Run Code Online (Sandbox Code Playgroud)

然后对于每个元素

arr[i] = new T{data};
Run Code Online (Sandbox Code Playgroud)

现在我想知道它是否安全、有益(更快)和可能,如果不是单独分配每个对象,我可以在堆上创建第二个数组并将每个对象的指针保存在第一个数组中。然后使用(并删除) 这些对象稍后就好像它们是单独分配的一样。

=> 在堆上分配数组是否比单独分配每个对象更快?

=> 在数组中分配对象并稍后忘记数组是否安全?(我觉得这听起来很愚蠢)

链接到我的 github 仓库:https : //github.com/LinuxGameGeek/personal/tree/main/c%2B%2B/vector

谢谢你的帮助 :)

c++ arrays vector heap-memory dynamic-memory-allocation

0
推荐指数
1
解决办法
124
查看次数

如果没有正确分配,我应该在 C 中释放内存吗?

例如,当声明一个 malloc 然后检查它是否为 NULL 以查看它是否已正确分配时,如果它为 null,我应该释放内存,例如:

int *p;
p = (int *)malloc(sizeof(int)); 
  
    if (p == NULL)
    {
        free(p); //Should I free here or will it create an error?
        return NULL;
    }    
Run Code Online (Sandbox Code Playgroud)

c memory dynamic-memory-allocation

0
推荐指数
1
解决办法
66
查看次数

C++ 中的动态数组实现

我正在尝试使用 C++ 实现动态数组。但是,我的resize()功能似乎无法正常工作。没有错误或警告。我做了一些研究并尝试查看互联网上找到的其他实现,但无法解决该问题。我把我的代码放在下面。

#include <iostream>

class Array
{
private:
    int* arr;
    int size = 0;
    int capacity = 1;

public:
    Array() { arr = new int[capacity]; }

    Array(int capacity)
        :
        capacity(capacity)
    {
        arr = new int[capacity];
    }

    int length() const { return size; }

    bool is_empty() const { return (length() == 0); }

    int get(int index) const { return arr[index]; }

    void set(int index, int value) { arr[index] = value; }

    void resize()
    {
        capacity *= 2;
        int* …
Run Code Online (Sandbox Code Playgroud)

c++ class definition member-functions dynamic-memory-allocation

0
推荐指数
1
解决办法
1135
查看次数

为什么 scanf 没有将整数存储在正确的数组位置?

我正在创建一个动态分配的二维 int 数组,并尝试使用 scanf 直接读取用户输入,但这无法正常工作。第一次读取是正确的,并将用户输入的值存储在 [0][0] 处,但第二次读取将值存储在 [1][0] 而不是 [0][1] 处,第三次及后续读取则不正确。 t 将值存储在数组中的任何位置(我猜最终会出现在边界之外的随机内存中?)。索引似乎是错误的,但我已经仔细检查过它们,并且可以在调试器中看到它们的正确值。

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

#define ROW_SIZE 2
#define COL_SIZE 6

typedef int myMatrix[ROW_SIZE][COL_SIZE];

int main(void) {
  myMatrix *pMatrix = (myMatrix *)malloc(sizeof(int) * (ROW_SIZE * COL_SIZE));

  for (int i = 0; i < ROW_SIZE; ++i) {
    for (int j = 0; j < COL_SIZE; ++j) {
      printf("Enter row %d column %d: ", i, j);
      scanf("%d", pMatrix[i][j]);
    }
  }

  // Do stuff with matrix

  return 0;
}
Run Code Online (Sandbox Code Playgroud)

如果我将用户输入读取到临时 int …

c arrays multidimensional-array dynamic-memory-allocation

0
推荐指数
1
解决办法
72
查看次数

C中多次循环失败后出现段错误

我正在做一个练习,创建一个数组并用整数填充元素。我首先将数组的长度输入到 malloc 中作为大小。然后,我在 for 循环中扫描数组中每个点的元素。

这是代码

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

int scaning(int ** array){
    int size;
    scanf("%d", &size);
    *array = malloc(sizeof(int)*size);
    //printf("%d\n", size);
    for (int i=0; i<=size; i++){
        int num;
        scanf("%d", &num);
        *array[i] = num;
    }

    return size;
}


int main(){
    
    int * array;
    int zero;
    zero = scaning(&array);
    //printf("%d\n", zero);
    printf("LOOPS\n");
    for (int i=0; i<= zero; i++){
        printf("%d\n", array[i]);
    }
    return 0;
}

Run Code Online (Sandbox Code Playgroud)

在我输入元素填充数组两次后,出现段错误。我通常输入 5 个数组的大小,输入 2 个数字,然后它就会崩溃。不知道我哪里出错了。有任何想法吗?

c for-loop pass-by-reference operator-precedence dynamic-memory-allocation

0
推荐指数
1
解决办法
39
查看次数