Hi guys. I am using a string made up of small letters, capital letters and numbers. This is a 26+26+10 = 62 length string:
Code:
char string[] = {'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9'};
By making all combinations possible, joining 3 characters at a time, I have 62*62*62 = 238328 combinations possible, starting in 'AAA' and ending up in '999' (following the order that appears on the string above). Each combination of 3 characters is 3 bytes long, so this would occupy 3 * 238328 bytes = 714984 bytes
I want to save these generated combinations in a file, but I dont want to generate one and save and so on! What I want is to first generate them all in memory, and then save them all at a time.
For that, I allocate memory like this:
Code:
char* ptr;
ptr = (char *) calloc(714984, 1);
and then,
Code:
if (ptr == NULL) {
printf("\nError allocating dynamic memory! Exiting...\n");
return EXIT_FAILURE;
}
ptr_cpy = ptr;
for (i = 0; i < 62; i++) {
for (j = 0; j < 62; j++) {
for (k = 0; k < 62; k++) {
*ptr = string[i];
ptr++;
*ptr = string[j];
ptr++;
*ptr = string[k];
ptr++;
}
}
}
If I try to printf the last elements of ptr on screen, all goes well:
Code:
printf("Size of PTR: %d bytes\n\n", strlen(ptr)); -> (gives 714984)
printf("String: %c\n", ptr[714978]); -> shows 9
printf("String: %c\n", ptr[714979]); -> shows 9
printf("String: %c\n", ptr[714980]); -> shows 8
printf("String: %c\n", ptr[714981]); -> shows 9
printf("String: %c\n", ptr[714982]); -> shows 9
printf("String: %c\n", ptr[714983]); -> shows 9
AND NOW THE FUNNY PART (and my question):
If i allocate less memory, say 712662 :
ptr = (char *) calloc(712662, 1);
it works perfectly too and also shows all perfectly generated combinations!!!!!!
If I allocate one less byte , 712661, it crashes! The threshold seems to be 712662! I dont understand why, because i thought it must be 714984.
Can you help me to understand what is going on ?
Thank you.