There are functions in C for allocating memory malloc and realloc . So I quickly sketched the code:

 char *test; test = (char *)malloc(sizeof(char) * 2); // По идеи я выделил место под 2 символов char strcpy(test, "Hello world"); // Тут я записал Hello world хотя я выделил место всего под 2 символа printf("%d", sizeof(test)); // Тут мне показывает 8, что это за 8, откуда оно взялось ? test = (char *)realloc(test, sizeof(char) *4); // Добавляем еще место под 4 символа ( непонятно зачем правда, потому что Hello World как-то записалось хотя я выделил всего место под 2 символа printf("%d", sizeof(test)); // Выводится 8, опять 8..откуда? free(test); 

Can you please explain how this works in general? Maybe I do not understand something.

  • one
    For reference: sizeof(char) by definition equal to 1 - αλεχολυτ
  • Well this is me vkurse - Corle
  • you can't tell by code :) - αλεχολυτ
  • I specifically do this so that it becomes a habit to write like that, because different types have different values - Corle
  • in that case, it makes sense, yes. - αλεχολυτ

1 answer 1

 char *test; 

Announced pointer

 test = (char *)malloc(sizeof(char) * 2); // По идеи я выделил место под 2 символов char 

Exactly

 strcpy(test, "Hello world"); // Тут я записал Hello world // хотя я выделил место всего под 2 символа 

Recorded in memory, in which you can not write. Undefined behavior also includes this behavior when the recording is performed beyond the allowed limits silently :)

 printf("%d", sizeof(test)); // Тут мне показывает 8, что это за 8, откуда оно взялось ? 

The pointer size (which is your test variable) on your system is 64-bit

 test = (char *)realloc(test, sizeof(char) *4); // Добавляем еще место // под 4 символа ( непонятно зачем правда, потому что // Hello World как-то записалось хотя я выделил всего место под 2 символа 

Not yet, but just for 4 characters.

 printf("%d", sizeof(test)); // Выводится 8, опять 8..откуда? 

That is how much memory space is occupied by the test variable. Not what she points to.

 free(test); 

Freeing allocated memory.

  • Can you give an example of the correct code? But I don’t understand something)) - Corle
  • one
    Just allocate enough memory, that's all. And - if it comforts you - then this code, compiled by VC ++, leads to crash. It is impossible to find out by the pointer how much memory is allocated in C / C ++ - so you have to remember this value yourself. - Harry
  • It’s actually possible to learn, but such an operation is already with itself UB. cyberforum.ru/post4956590.html - user194374
  • Pointer определили , not only объявили . - αλεχολυτ
  • one
    @kff This is not C / C ++. And even if you know the structure of the manager, then the pointer that you get somewhere may not be at the beginning ... - Harry