在malloc c上出现分段故障

问题描述 投票:0回答:1

我一直在看其他帖子,想弄明白这个问题,但一直没有办法.我在调用一个需要指针的结果的函数,像这样。

int plaintext_len = 0;
unsigned char *plaintext = NULL;
plaintext_len = token_decrypt( login_token, &plaintext );

token_decrypt 解密效果很好,像这样:下面的 gcm_decrypt 函数返回明文长度,并将明文文本存储在 my_plaintext.

int token_decrypt( const char *jwt_token, unsigned char **plaintext ) {
        int ret = 0;
        unsigned char my_plaintext[1024];
        ...
        ret = gcm_decrypt( 
            (unsigned char*)token_decoded.c_str(),
            ciphertext_len, 
            (unsigned char*)aad.c_str(), 
            aad_len, 
            (unsigned char*)tag.c_str(),
            (unsigned char*)decoded_key.c_str(), 
            (unsigned char*)iv.c_str(), 
            iv_len, 
            my_plaintext 
        );
        printf("my_plaintext: '%s'\n", my_plaintext ); <---- prints correctly the result.
        *plaintext = (unsigned char *)malloc( sizeof(char) * ret );
        memcpy( *plaintext, my_plaintext, ret );
        printf("token plaintext: '%s'\n", plaintext );
        return ret;

但是,执行segfaults在

*plaintext = (unsigned char *)malloc( sizeof(char) * ret );
c pointers malloc
1个回答
0
投票

我决定在调用函数之前进行分配。

plaintext = (unsigned char *)malloc( sizeof(char)*ret );

0
投票

你必须为空终结符多分配一个字节 而且你必须传递给... *plaintextprintf(),不 plaintext.

        *plaintext = (unsigned char *)malloc( sizeof(char) * (ret + 1) );
        if (*plaintext) {
            memcpy( *plaintext, my_plaintext, ret );
            (*plaintext)[ret] = '\0';
            printf("token plaintext: '%s'\n", (char *)(*plaintext) );
            return ret;
        } else {
            /* emory allocation error */
            return -1;
        }

如果你的目标是POSIX系统,你应该使用 strndup() 这比自己分配内存更不容易出错。

        *plaintext = (unsigned char *)strndup((char *)my_plaintext, ret);
        if (*plaintext) {
            printf("token plaintext: '%s'\n", (char *)(*plaintext) );
            return ret;
        } else {
            /* emory allocation error */
            return -1;
        }
© www.soinside.com 2019 - 2024. All rights reserved.