Answer the question
In order to leave comments, you need to log in
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;
}
Answer the question
In order to leave comments, you need to log in
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.
From myself, I’ll add there are functions for clearing memory that fill the buffer at your address with some value, usually 0
"... 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
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 questionAsk a Question
731 491 924 answers to any question