Implementation of Realloc in C
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 | int getmin(int a, int b) { return a;lt;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()分配的内存大小。
但是,您总是可以做类似的事情来模拟您想要的。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 | #include ;lt;stdio.h;gt; #include ;lt;stdlib.h;gt; #include ;lt;string.h;gt; 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 ", msize); if (size ;lt;= 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 ",getsize(aa)); strcpy(aa,"my cookie"); bb = reallocation(aa,100); printf("bb size is %d ",getsize(bb)); printf(";lt;%s;gt; ",bb); free(bb); } |
我相信
另外,我应该注意,在相同情况下,即使
the memory allocated by malloc gets initialized to zero, so i am checking for that condition.
不对从草稿:
Description
2 The malloc function allocates space for an object whose
size is specified by size and whose value is indeterminate.
您的
My reallocation function is working fine.
您甚至都没有固定路线-某些类型的路线可能会失败。阅读这个问题。
Also can we do inplace reallocation if the size of the previously allocated memory is greater than the new required?
就地重新分配意味着什么?这不是一个简单的禁忌法吗?