相关疑难解决方法(0)

malloc()和free()如何工作?

我想知道如何mallocfree工作.

int main() {
    unsigned char *p = (unsigned char*)malloc(4*sizeof(unsigned char));
    memset(p,0,4);
    strcpy((char*)p,"abcdabcd"); // **deliberately storing 8bytes**
    cout << p;
    free(p); // Obvious Crash, but I need how it works and why crash.
    cout << p;
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

如果答案在记忆水平上是深入的,如果可能的话,我将非常感激.

c c++ malloc free memory-management

263
推荐指数
9
解决办法
14万
查看次数

malloc()是如何在内部实现的?

任何人都可以解释malloc()内部如何运作

我有时会这样做strace program,我看到很多sbrk系统调用,正在man sbrk讨论它的使用情况,malloc()但不多.

c memory malloc system-calls sbrk

112
推荐指数
3
解决办法
12万
查看次数

为什么malloc没有被释放?

#include <stdio.h>
#include <stdlib.h>
typedef struct node{
    struct node *pre;
    struct node *next;
    int data;
}NODE; //struct declaration

int main(){

    NODE *new_node=(NODE*)malloc(sizeof(NODE)); //memory allocation

    printf("\nnew_node addr: %d\n",new_node);

    free(new_node); //deallocation

    printf("new_node addr: %d\n",new_node);


}
Run Code Online (Sandbox Code Playgroud)

结果:

new_node addr: 2097152
new_node addr: 2097152
Program ended with exit code: 0
Run Code Online (Sandbox Code Playgroud)

结果为何相同?
我释放new_node的内存.但是new_node有地址.
为什么??

c malloc free

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

标签 统计

c ×3

malloc ×3

free ×2

c++ ×1

memory ×1

memory-management ×1

sbrk ×1

system-calls ×1