OpenJDK源码赏析之四(jli_util中的工具函数)

本文详细分析了OpenJDK中内存分配、重新分配、释放及字符串复制的相关函数,如JLI_MemAlloc、JLI_MemRealloc、JLI_StringDup和JLI_MemFree。这些函数本质上都是对C语言的malloc、realloc、strdup和free的封装,当内存操作失败时,会打印错误信息并异常退出。同时,JLI_StrCCmp用于字符串比较,通过JLI_StrNCmp实现。
摘要由CSDN通过智能技术生成

上一篇:

 OpenJDK源码赏析之三:Java命令参数的读取_星空_MAX的博客-CSDN博客

不承接上一篇,这篇单独开始分析jli_util.h(java工具函数)里的一些函数

JLI_MemAlloc

/*
 * Returns a pointer to a block of at least 'size' bytes of memory.
 * Prints error message and exits if the memory could not be allocated.
 */
void *
JLI_MemAlloc(size_t size)
{
    void *p = malloc(size);
    if (p == 0) {
        perror("malloc");
        exit(1);
    }
    return p;
}

可以看到jJLT里面的内存分配实际上用了C语言自带的malloc函数,这里如果分配失败则会输出错误信息,并执行,exit(1)表示异常退出,这个1是返回给操作系统的

关于malloc函数精解,可以看另一篇文章

linux-malloc底层实现原理_mmshixing的博客-CSDN博客_malloc的底层实现

JLT_MemeRealloc

/*
 * Equivalent to realloc(size).
 * Prints error message and exits if the memory could not be reallocated.
 */
void *
JLI_MemRealloc(void *ptr, size_t size)
{
    void *p = realloc(ptr, size);
    if (p == 0) {
        perror("realloc");
        exit(1);
    }
    return p;
}

重新分配内存,也同样是调用C语言的

JLI_StringDup

/*
 * Wrapper over strdup(3C) which prints an error message and exits if memory
 * could not be allocated.
 */
char *
JLI_StringDup(const char *s1)
{
    char *s = strdup(s1);
    if (s == NULL) {
        perror("strdup");
        exit(1);
    }
    return s;
}

strdup可以直接把要复制的内容赋值给没有初始化的指针,因为它会自动分配空间给目的指针

strcpy的目的指针一定是已经分配内存的指针

JLI_MemFree

/*
 * Very equivalent to free(ptr).
 * Here to maintain pairing with the above routines.
 */
void
JLI_MemFree(void *ptr)
{
    free(ptr);
}

呃,和free一样,官方解释为和上面保持一样

JLI_StrCCmp

int
JLI_StrCCmp(const char *s1, const char* s2)
{
   return JLI_StrNCmp(s1, s2, JLI_StrLen(s2));
}

在jli_util.h中找到宏定义

#define JLI_StrNCmp(p1, p2, p3) strncmp((p1), (p2), (p3))

将p1函数和p2函数进行比较,比较p3个字节,

p1=p2则等于0,

p1>p2则返回值大于0,

p1<p2则返回值小于0

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值