when compiled will reserve an array of 50 elements.
Malloc it is said goes around this because it is not needed to know, during compile time, how many variables will be needed.
This does not make sense because you have to put malloc(SIZE). You need to tell it its size so ofcoarse you must know during compile time how much space you need... Does anyone see my confusion?
Well of course malloc needs to know the size you are allocating.. but that does not mean this value will be known at compile time.
1 2 3 4 5 6 7
int userInput;
cin >> userInput;
char array1[userInput]; // Obviously an error since userInput is unknown at compile time.
char* array2 = malloc(userInput); // No problem here, but dont forget to delete me
// when I'm no longer needed!
1 #include <stdio.h>
2 #include <stdlib.h>
3
4 int main ()
5 {
6
7 int size,n;
8
9 printf ("How long do you want the string? ");
10 scanf ("%d", &size);
11 char buffer[size]; // it still can get the size of the array from user.
12
13 for (n=0; n<size; n++){
14 buffer[n]=rand()%26+'a';
15 buffer[size]='\0';}
16
17 printf ("Random string: %s\n",buffer);
18
19 return 0;
20
21 }
The code run well with no errors. So, what is the purpose of malloc()? Please help me.
int size,n;
printf ("How long do you want the string? ");
scanf ("%d", &size);
char buffer[size]; // it still can get the size of the array from user.
Arrays with a length not known at compile time (variable length arrays) are allowable by the C99 standard. Some compilers, such as GCC, allow this. However, variable length arrays are not allowed in C++. You can be warned about using non-conformant C++ by using the -pedantic flag in GCC. In strict C++, you will have to use malloc (or calloc) or new [] for creating variable length arrays. new [] will have to be used if you're creating an array of objects and you want their constructors to be called.
std::malloc( ) allocates the specified amount of bytes and returns the allocated block to the calling function. It's common to cast the returned block to the desired type. However, std::malloc( ) doesn't call constructors. std::free( ) on the other hand, releases the resources (deletes) allocated by std::malloc( ).
Note that you should never mix new and std::free( ), delete and std::malloc/calloc( )[std::calloc( )?].
[std::calloc( )]: std::calloc( ) is another variation of std::malloc( ). It initializes all allocated elements to zero after allocation.