c - malloc 复制中的分段错误
问题描述
我正在尝试实现The C programming language一书中的一个示例。该示例复制了malloc的简化版本。我的实现产生了分段错误。函数 alloc 和 afree 基本上是从书中抄来的。我正在尝试在 main.js 中使用这些功能。据我了解,只要两个地址都在同一个数组中,*(pointer+i) 表达式就会给我存储在指针旁边的地址中的值。它应该是隐含的满足,但显然,这还不够。
我如何才能真正使用函数 alloc 和 afree 创建动态数组?
#include <stdio.h>
int *alloc(int);
void afree(int *);
/* RETURNS SEGMENTATION FAULT, WHY? */
int main()
{
int *dyna_arr;
dyna_arr = alloc(50);
/* fill the array with integers */
for (int i = 0; i < 50; i++)
{
*(dyna_arr+i) = i;
}
for (int i=49; i>=0;i--)
{
printf(" %d", *(dyna_arr+i));
}
afree(dyna_arr);
}
#define ALLOCSIZE 10000
static int allocbuf[ALLOCSIZE];
static int *allocp =allocbuf; /* next free position in buffer */
/* alloc: return pointer to n ints */
int *alloc(int n)
{
if (allocbuf + ALLOCSIZE - allocp >= n) /* is there enough space in the buffer? */
{
allocp += n;
return allocp - n;
}
else /* not enough space */
{
return 0;
}
}
/* afree: free the storage pointed to by p */
/* Only possible in LIFO fashion */
void afree(int *p)
{
if (p >= allocbuf && p < allocbuf + ALLOCSIZE)
{
allocp = p;
}
}
解决方案
问题是
if (allocbuf + ALLOCSIZE - allocp <= n) /* is there enough space in the buffer? */
你的比较是错误的。应该available memory >= n
只是您的检查if available memory <= n
和返回0
;
下面的修改应该工作
if (((allocbuf + ALLOCSIZE) - allocp) >= n) /* is there enough space in the buffer? */
推荐阅读
- python - Docker 下 Python 中的 Selenium Chrome Web 驱动程序 - 等待下载过程完成
- c++ - 具有释放-获取内存排序的半无锁 spsc 队列
- javascript - 使用 react-native-track-player 从 flatlist 播放选定的歌曲
- php - 来自win do unix的ssh2 scp通过php不起作用
- python - ax.text() 的行为不像我认为的那样:(
- video - 如何避免 ffmpeg filter_complex 覆盖文件的 fps?
- google-chrome - 如何通过 chrome 扩展获利?
- python-3.x - 无法以与模型训练的图像形状相同的图像形状运行 model.predict()
- php - 在 Heroku 上托管 Laravel API 的缓慢响应和错误
- c# - 将c#集合序列化为视图中的jquery数组以通过ajax方法传递给控制器