gpt4 book ai didi

c - 在C中实现Realloc

转载 作者:行者123 更新时间:2023-11-30 17:29:52 26 4
gpt4 key购买 nike

int getmin(int a, int b)
{
return a<b?a:b;
}


void *reallocation(void *ptr, size_t size) //size_t in bytes
{

void *newptr;


int msize;
msize = getsize(ptr);

msize = getmin(msize, size);

printf("msize = %d", msize);

newptr = malloc(size);
newptr = memcpy(newptr, ptr, msize);
free(ptr);


return newptr;

}


我已经实现了自己的重新分配,并且为了使用malloc获得分配的内存大小(但是我知道在c中没有任何方法可以执行此操作)。

我的重新分配功能在我的系统上运行正常
我们如何获得malloc()分配的内存大小。

如果先前分配的内存大小大于所需的新内存,我们还可以进行就地重新分配吗?

最佳答案

没有可移植的方法来获取malloc()分配的内存大小。

但是,您总可以做类似的事情来模拟您想要的东西。

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

void myfree(void * p) {
size_t * in = p;
if (in) {
--in; free(in);
}
}

void * mymalloc(size_t n) {
size_t * result = malloc(n + sizeof(size_t));
if (result) { *result = n; ++result; memset(result,0,n); }
return result;
}

size_t getsize(void * p) {
size_t * in = p;
if (in) { --in; return *in; }
return -1;
}

#define malloc(_x) mymalloc((_x))
#define free(_x) myfree((_x))

void *reallocation(void *ptr,size_t size) {
void *newptr;
int msize;
msize = getsize(ptr);
printf("msize=%d\n", msize);
if (size <= msize)
return ptr;
newptr = malloc(size);
memcpy(newptr, ptr, msize);
free(ptr);
return newptr;
}
int main() {
char * aa = malloc(50);
char * bb ;
printf("aa size is %d\n",getsize(aa));
strcpy(aa,"my cookie");
bb = reallocation(aa,100);
printf("bb size is %d\n",getsize(bb));
printf("<%s>\n",bb);
free(bb);
}

关于c - 在C中实现Realloc,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25470248/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com