0
点赞
收藏
分享

微信扫一扫

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

大沈投资笔记 2022-04-15 阅读 88
c++java

上一篇:

 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

举报

相关推荐

0 条评论