标签: dynamic-memory-allocation

C 如何释放动态分配数组的所有字节?

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

int main(){

    int * ptr = (int*)malloc(sizeof(int)*100); // Allocated space for 100 integers

    // Some code

    free(ptr); // Calling free with ptr as argument

    return 0;
}
Run Code Online (Sandbox Code Playgroud)
  1. 如何释放所有 400 字节(在我的例子中)?ptr仅包含内存中一个字节的地址,而且我没有传递任何其他参数来指定动态数组的大小,以便它可以运行循环并释放所有字节

  2. 如果我这样做会发生什么:

    ptr++;
    free(ptr);
    
    Run Code Online (Sandbox Code Playgroud)
  3. 既然我们无法通过给出指针来检索堆中数组的大小,那么这意味着malloc()不知道保留了多少字节,ptr那么为什么它不从前一个数组的中间开始分配另一个堆内存呢?

c malloc free pointers dynamic-memory-allocation

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

C 代码分配的内存多于应有的内存

对于一门课程,我正在用 C 语言进行乘法表样式的练习。该代码功能齐全,但自动测试显示它分配了 416 个字节,而它应该只分配 376 个字节。这是值 a=2,b =9,c=11,d=17。我已经通过 valgrind 运行了代码,并打开了所有可能的额外细节,但它并没有真正帮助。

我尝试将标题行生成写入为主时间表创建的一部分,但它最终使用的内存比我当前的方法更多。

destroyTimes 函数也不应该有问题,因为 valgrind 没有报告任何泄漏。

这是 times.c

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

Times* createTimes(uint a, uint b, uint c, uint d) {
  int i,j;
  int rows=d-c+2;
  int cols=b-a+2;
  
  Times* ret = malloc(sizeof(Times));
  uint** kert = malloc(sizeof(uint*)*rows);

  if (!ret) {
    return NULL;
  }

  ret->a=a;
  ret->b=b;
  ret->c=c;
  ret->d=d;

  kert[0] = malloc(sizeof(uint)*(cols+1)); 
  kert[0][0] = 1;

  for(j=1;j<cols;j++) {
    kert[0][j] = a;
    a++;
  }
  a = ret->a;

  for(i=1;i<rows;i++) {
    kert[i] = malloc(sizeof(uint)*(cols+1));
    for(j=0;j<cols;j++) …
Run Code Online (Sandbox Code Playgroud)

c dynamic-memory-allocation

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

无法使用 realloc 调整内存块大小

我编写了一个简单的程序来实现基于动态数组的堆栈。realloc已用于调整我用来存储堆栈元素的容器的大小。

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

void stack_push(int **stack, int *stackSize, int element);
int stack_pop(int **stack, int *stackSize);

int main()
{
    char ch;
    int *stack = NULL, stackSize = 0;
    
    do
    {
        printf("\n1. Push\n");
        printf("2. Pop\n");
        printf("Exit (0)\n");
        printf("Enter choice : ");
        scanf("%c", &ch);

        switch(ch)
        {
            case '1':
                stack_push(&stack, &stackSize, 1);
                break;
            case '2':
                printf("%d\n", stack_pop(&stack, &stackSize));
                break;
            case '0':
                break;
        }
    } while (ch != '0');

    return 0;
}

void stack_push(int **stack, int *stackSize, int element)
{
    if …
Run Code Online (Sandbox Code Playgroud)

c stack realloc segmentation-fault dynamic-memory-allocation

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

C编程面试题,关于动态内存分配

如果你想在堆中动态分配8字节内存,但这8字节内存不是连续可用的。它在堆中分别以 5 字节和 3 字节的形式提供。那么可以分配内存吗?如果是,怎么办?

如果是,我们可以只使用 malloc 或 malloc 与 calloc

c malloc pointers dynamic-memory-allocation

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

SomeClass*initialEl = new SomeClass [5];

应该SomeClass*initialEl = new SomeClass [5]; 必须编译,假设SomeClass没有非公开声明的默认构造函数?考虑:

/*
 * SomeClass.h
 *
 */

#ifndef SOMECLASS_H_
#define SOMECLASS_H_

class SomeClass
{

public:
    SomeClass(int){}
    ~SomeClass(){}
};

#endif /* SOMECLASS_H_ */


/*
 * main.cpp
 *
 */

#include "SomeClass.h"

int main()
{
    SomeClass* initialEl = new SomeClass[5];

    delete[] initialEl;

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

c++ memory-management class dynamic-memory-allocation dynamic-arrays

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

使用new分配派生类数组的问题

我有一个简单的程序

$ cat a.cpp 
#include <iostream>
class MyClass {
    public:
        virtual void check() {
            std::cout << "Inside MyClass\n";
        }
};

class MyClass2: public MyClass {
    public:
        int* a;
        virtual void check() {
            std::cout << "Inside MyClass2\n";
        }
};

int main() {
    MyClass *w, *v;
    w = new MyClass2[2];
    v = new MyClass2;
    std::cout << "Calling w[0].check\n"; w[0].check();
    std::cout << "Calling v->check\n"; v->check();
    std::cout << "Calling w[1].check\n"; w[1].check();
}
$ g++ a.cpp
$ ./a.out 
Calling w[0].check
Inside MyClass2
Calling v->check
Inside …
Run Code Online (Sandbox Code Playgroud)

c++ derived-class segmentation-fault new-operator dynamic-memory-allocation

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

struct self referencing

我到处都有语法错误,对ADT语法和内存处理的理解不好.我需要一个在next和中引用自身(其他部分)的结构prev.我做得对吗?我收到错误......

struct _header * header;

typedef struct _header {
    int signiture;
    int size;
    header_t* next;
    header_t* prev;
} header;
Run Code Online (Sandbox Code Playgroud)

我还想用一个头来初始化内存中的前32个字节(这也不顺利......):

//this is to reference the memory block later
static int *free_list_ptr;

void function(u_int32_t size){
    memory = (byte*) malloc(size);
    header firstHead = malloc(sizeof(_header));
   free_list_ptr = firstHead = memory;
   firstHead->prev = free_list_ptr;
   firstHead->next = free_list_ptr;
}
Run Code Online (Sandbox Code Playgroud)

c struct pointers dynamic-memory-allocation

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

动态分配2d数组并初始化它(分段错误)

我正在学习C,我试图为2D数组分配内存(我从用户那里得到它们的数组的维度),但是在我尝试初始化之后我遇到了分段错误.我的代码是这样的:

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

int main()
{
   printf("give the dimensions!\n");
   int row,col,i,j; 
   int **myArray;

   printf("\nrows = ");
   scanf("%d", &row);
   printf("columns = ");
   scanf("%d", &col);
   myArray = malloc(row*sizeof(*myArray) + col*sizeof(**myArray));

   printf("Init the array: \n");
   for (i = 0; i < row; i++)
   {
       for (j = 0; j <col ; j++)
       {
           scanf("%d", &myArray[i][j]);
       }
   }

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

如果我更改数组myArray[2][2]并省略malloc语句它工作正常..

c multidimensional-array dynamic-memory-allocation

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

如何声明一个空的char*并动态增加大小?

假设我正在尝试执行以下操作(这是我想要实现的一个子问题):

int compareFirstWord(char* sentence, char* compareWord){
      char* temp; int i=-1;
      while(*(sentence+(++i))!=' ') { *(temp+i) = *(sentence+i); }
      return strcmp(temp, compareWord); }
Run Code Online (Sandbox Code Playgroud)

当我跑步时compareFirstWord("Hi There", "Hi");,我在复制线上遇到错误.它说我正在使用temp未初始化.然后我使用char* temp = new char[];在这种情况下,函数返回1而不是0.当我调试时,我看到temp以一些长度为16的随机字符开始并strcmp因此而失败.

有没有办法声明一个空的char*并动态增加大小只是我需要的长度和内容?有什么办法让这个功能起作用?我不想用std::string.

c c++ char strcmp dynamic-memory-allocation

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

为什么我收到此错误以及如何解决此问题:munmap_chunk():无效指针:0x0000000000400694***Hello WorldAborted

我写了以下程序:

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

int main(void)
{
        char *s;
        s = (char*)malloc(15);
        s = "Hello World";
        printf("%s",s);
        free(s);
        return 0;
  }
Run Code Online (Sandbox Code Playgroud)

没有编译错误.我得到这个运行时错误: *./s'错误:munmap_chunk():指针无效:0x0000000000400694* Hello WorldAborted

为什么我会收到此运行时错误,如何解决?是因为在调用malloc之后,s收到了某个地址,并且赋值s ="Hello World"修改了s的地址,但是当执行free(s)时,发送给free的指针不是那个那是由malloc返回的?

提前致谢!

c string dynamic-memory-allocation

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