Darko S Darko S - 2 months ago 13
C Question

Heap Corruption Detected C

I've been dangling with C and a bit of cryptography, anyways I try to dynamically allocate a string to input a plain text and a key which i use to get a cypher text. Program works until I decide to free the allocated memory. then produces an error stating: HEAP CORRUPTION DETECTED: after Normal block (#73) at this and this address; checked all the other posts, nothing, I'm confused, pls help. Here's the code :

int main(int argc, char *argv[])
int plainSize = 0;
int keySize = 0;

InputInteger(keySize,"key size");
InputInteger(plainSize,"plaintext size");

char *plaintext = (char*)malloc((plainSize + 1) * sizeof(char));
char *key = (char*)malloc((keySize + 1) * sizeof(char));
char *cypher = (char*)malloc((plainSize + 1) * sizeof(char));

InputString(plaintext, "plaintext");
InputString(key, "key");

cypher=ViginereEncrypt(plaintext, key);
printf("\n%s encypted with Viginere key %s is %s", plaintext, key, cypher);


char *ViginereEncrypt(char *plaintext,char *key)
int i = 0;
char *cypherText = (char*)malloc((strlen(plaintext) + 1)*sizeof(char));
printf("\n%d\n", strlen(plaintext) + 1);
for (i = 0;i < strlen(plaintext);i++)
*cypherText++ =(*plaintext++ - 'A' + *key++ - 'A' -1) % ('Z' - 'A') + 'A';
cypherText[i] = '\0';
return cypherText;
void InputInteger(int myInteger,char name [100])
printf("Input a number for %s : ",name);
scanf("%d", &myInteger);
void InputString(char myString[],char name[100])
printf("Input a string for %s : ",name);
scanf("%s", myString);

Is the problem with the allocation inside the function? Think it shouldn't be since I "copied" the cypher to the function return and then freed it. Thanks in advance!


The function call InputInteger(keySize,"key size"); cannot put a value to keySize. Both keySize and plainSize will remain as 0. So you are allocating 1 byte of memory for each string, only enough for a terminator. Computer melts.

I suggest these changes, firstly to pass back the input value

void InputInteger(int *myInteger, char name [100])     // add the *
   printf("Input a number for %s : ", name);
   scanf("%d", myInteger);                             // remove the &

then change the way you call it.

InputInteger(&keySize, "key size");                    // add the &
InputInteger(&plainSize, "plaintext size");            // add the &

so that you pass the address of the variable you wish to alter.

Edit: That is not to say there are no other vulnerabilites in the code. The string length may be a negative number, you should be doing some input validation. Also the InputString function is open to malicious attack or accidental fault, where the user can say the string length is 2 and then wreck the stack, with some curious larger input which takes over the machine because it is executable code which the perp has placed there to steal your beans.