A
A
Artyom2013-01-22 13:52:15
C++ / C#
Artyom, 2013-01-22 13:52:15

Interesting/strange use of malloc - what's the point?

While recently studying the libfetch code , I came across a piece of code that is not entirely clear to me:

if ((str = malloc(((l + 2) / 3) * 4 + 1)) == NULL)
    return (NULL);

This is in the http_base64 function at the very beginning of it. Is there some alignment going on here? Or is it because of the base64 length of the string?

Answer the question

In order to leave comments, you need to log in

4 answer(s)
J
jcmvbkbc, 2013-01-22
@alius

To represent a string of N 8-bit characters, you need (N * 8 / 6) = (N / 3 * 4) 6-bit characters (base 64).
(l + 2) / 3 is a division by 3 rounded up because the number of characters must be an integer.
+ 1 is for zero at the end of the string.

A
agmt, 2013-01-22
@agmt

Ohhh, the expression is much more difficult to decipher than it is to understand what is happening there, and all because of the font in which the "1" is so similar to the "l".

B
barker, 2013-01-22
@barker

Well, yes, I think it's obvious. The length of the final line is calculated, which refers to the original (and this is l in this formula) as 4/3.

W
woolfcod, 2017-02-11
@woolfcod

Hello.
Sorry for posting in this thread.
Just in the creation of the question, the button "publishing is not available"
Here's the question:
The program recursively searches for files on disks.
The program allocates memory for writing to a file.
Allocation
dword databuf = n;
auto buf = (byte*)malloc(databuf)
memcpy(buf,data,databuf)
The program crashes, the debugger shows here
memcpy(buf,data,databuf);

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question