L
L
lutokris2021-03-25 14:12:22
MySQL
lutokris, 2021-03-25 14:12:22

Why does memory allocation for a string look out of pattern?

All good. I'm learning C++ by Schildt. Almost at the very beginning, I reached dynamic memory allocation and was already seriously puzzled by the following. After all, based on the syntax of memory allocation - (T *) malloc(n * sizeof(T)); then we should probably write
(char*) malloc (len * sizeof(char)); And for some reason they write (char *) malloc (len + 1); thereby sort of allocating memory only for the character '10'. In general, I have no idea why they write this way, because when they allocate an int for a dynamic array, they write (int*) malloc(n * sizeof(int);

and this is an example from the book

strtype::strtype(char *ptr) {
     len = strlen(ptr);   
     p = (char*) malloc(len + 1);
     if (!p) 
     {
            cout << "Ошибка выделения памяти" << endl;
            exit; 
     }
     strcpy(p, ptr);
}

Answer the question

In order to leave comments, you need to log in

4 answer(s)
L
Lazy @BojackHorseman MySQL, 2018-03-17
@JackShcherbakov

SELECT *
FROM orders
ORDER BY amount DESC
LIMIT 1

R
Ruslan., 2018-03-17
@LaRN

You can try this:
SELECT OrderId, MAX(Amount) AS Amn
FROM Orders
GROUP BY OrderId
ORDER BY Ann DESC
LIMIT 1

W
Wataru, 2021-03-25
@lutokris

When you allocate an array of n elements of type T you need n*sizeof(T) memory.
When you allocate a string of n characters, you need n+1 bytes of memory. Because each character is 1 byte, and you need space for n characters and a trailing '\0'. In C/C++, strings are always null-terminated. We must always remember about him and allocate a place for him.

L
lutokris, 2021-03-25
@lutokris

It seems that I understood why, as a parameter, malloc takes the size of the allocated area in bytes, respectively, since the size of the char character is 1 byte, we can pass the length of the string as the size of the allocated memory. And int is 4 bytes, so you need to allocate size n * sizeof(int) and let's say 10 integers will take up 40 bytes of space. True, it is still not completely clear why in the example the memory size was allocated for the Length + 1 string, and not just the Length of the string. It turns out, for example, under a string with a length of 10 characters - we will allocate "novalzhivi" for 10 bytes, and 11 bytes.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question