A
A
aldexnotproger2020-05-17 19:06:02
C++ / C#
aldexnotproger, 2020-05-17 19:06:02

How does malloc work?

There is this code

#include <malloc.h>
#include <stdio.h>
#include <string.h>

int main()
{
  char **text = (char**)malloc(1000);
  for(int i = 0; i < 1000; i ++)
  {
    text[i] = (char*)malloc(100);
  }	return 0;
}

1 - the size of the array element text[n] is 8 and not 100
2 - the array elements contain garbage

I have one question: why does all of the above work like this?
If the question is incorrect, please suggest an edit.

Answer the question

In order to leave comments, you need to log in

4 answer(s)
R
Rsa97, 2020-05-17
@aldexnotproger

1. You allocated not an array of characters, but an array of pointers to characters. Accordingly, the size of the pointer is 8 bytes.
2. C does not initialize the memory allocated by malloc.

V
Vladimir Korotenko, 2020-05-17
@firedragon

From myself, I’ll add there are functions for clearing memory that fill the buffer at your address with some value, usually 0

A
Alexey Lashko, 2020-05-19
@LASHKOAG

"... void * calloc( size_t number, size_t size );
The calloc function allocates a block of memory for an array of size - num elements, each of which occupies size bytes, and initializes all of its bits to zero."
cppstudio.com/post/846

B
bellatrix, 2020-05-29
@bellatrix

malloc(size_t size) allocates memory equal to size bytes. The example does not explicitly take this into account, and the following for loop will go through uninitialized memory (1000 bytes / 8 bytes pointer = 128). Your best bet is to use the calloc from the answer above, passing in the required number of elements and their size.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question