我想知道如何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)
如果答案在记忆水平上是深入的,如果可能的话,我将非常感激.
在我的机器上,时间A和时间B交换取决于是否A定义(这改变了calloc调用两个s 的顺序).
我最初将此归因于寻呼系统.奇怪的是,当
mmap用它代替时calloc,情况更加眩晕 - 两个循环都需要相同的时间,如预期的那样.可以看出strace,callocs最终导致两个
mmaps,因此没有返回已经分配的内存魔法.
我在Intel i7上运行Debian测试.
#include <stdlib.h>
#include <stdio.h>
#include <sys/mman.h>
#include <time.h>
#define SIZE 500002816
#ifndef USE_MMAP
#define ALLOC calloc
#else
#define ALLOC(a, b) (mmap(NULL, a * b, PROT_READ | PROT_WRITE, \
MAP_PRIVATE | MAP_ANONYMOUS, -1, 0))
#endif
int main() {
clock_t start, finish;
#ifdef A
int *arr1 = ALLOC(sizeof(int), SIZE);
int *arr2 = ALLOC(sizeof(int), SIZE);
#else
int *arr2 = ALLOC(sizeof(int), SIZE);
int …Run Code Online (Sandbox Code Playgroud) 我看到以下代码的结果存在一些差异:
#include <stdio.h>
#include <malloc.h>
#include <string.h>
int main(void)
{
char* ptr;
ptr = (char*)malloc(sizeof(char) * 12);
strcpy(ptr, "Hello World");
printf("%s\n", ptr);
printf("FREEING ?\n");
free(ptr);
printf("%s\n", ptr);
}
Run Code Online (Sandbox Code Playgroud)
让我解释:
在根据操作系统对printf的第三次调用中,我获得了不同的结果,在Windows中使用了gargabge caracters,在Linux和Unix系统中没有打印"Hello World".
有没有办法检查指针的状态,以了解内存何时被释放?
我认为这种印刷机制一直不可信.
Thnaks.
问候.
在我的大学练习中,我遇到了变量的奇怪行为.
/* Main parameters */
double sizeX, sizeY; /* Size of the global domain */
int nPartX, nPartY; /* Particle number in x, y direction */
int nPart; /* Total number of particles */
int nCellX, nCellY; /* (Global) number of cells in x, y direction */
int steps; /* Number of timesteps */
double dt; /* Stepsize for timesteps */
int logs; /* Whether or not we want to keep logfiles */
void ReadInput(const char *fname)
{
FILE *fp; …Run Code Online (Sandbox Code Playgroud)