用c语言编程查看电脑内存的代码
时间: 2024-03-09 15:51:05 浏览: 25
以下是用C语言编写的查看电脑内存的代码:
```c
#include <stdio.h>
#include <stdlib.h>
int main()
{
int *ptr, size;
printf("Enter the size of memory to allocate in bytes: ");
scanf("%d", &size);
ptr = (int*) malloc(size);
if (ptr == NULL)
{
printf("Memory allocation failed\n");
return 1;
}
printf("Memory allocated successfully\n");
// Accessing the allocated memory
for (int i = 0; i < size/sizeof(int); i++)
{
ptr[i] = i;
printf("Value at address %p: %d\n", &ptr[i], ptr[i]);
}
// Freeing the allocated memory
free(ptr);
printf("Memory freed successfully\n");
return 0;
}
```
这段代码首先提示用户输入要分配的内存大小,然后使用`malloc()`函数来分配内存。接着,通过循环遍历内存并打印出每个地址的值。最后,释放内存使用`free()`函数。