我想知道如何malloc和free工作.
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)
如果答案在记忆水平上是深入的,如果可能的话,我将非常感激.
任何人都可以解释malloc()内部如何运作
我有时会这样做strace program,我看到很多sbrk系统调用,正在man sbrk讨论它的使用情况,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有地址.
为什么??