ReAlloc如果在C实现 [英] Implementation of Realloc in C

查看:602
本文介绍了ReAlloc如果在C实现的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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;

}

我已经实现了我自己的realloc,为了使用malloc获得分配的内存的大小(但我知道没有任何方法在C)。

I have implemented my own realloc, and in order to get the size of the allocated memory using malloc(however i know there isn't any method for this in c).

我的再分配功能是我的系统上工作正常
我们如何获取由malloc分配的内存的大小()。

My reallocation function is working fine on my system How do we get the size of the memory allocated by malloc().

此外,我们可以做到就地重新分配,如果$ P $的大小pviously分配的内存比新要求?

Also can we do inplace reallocation if the size of the previously allocated memory is greater than the new required?

推荐答案

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

There is no portable way to get the size of memory allocated by malloc().

不过,人们总是可以做这样的事情来模拟你想要的。

However, one can always do something like that to simulate what you want.

#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);
}

这篇关于ReAlloc如果在C实现的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆