I am trying to compile and code written in C under linux, and got this error message:
glibc detected malloc(): memory corruption
and I cannot find out why...
the substring() just return you part of the original string by giving the starting index and length. e.g. substring("this is example",0,4) = "this";
char *substring(char* str, int start, int length) {
char *newString = (char *)malloc(length * sizeof(char));
int i, x = 0;
int end=start+length-1;
for(i = start ; i <= end; i++){
newString[x++] = str[i];
}
newString[x] = '\0';
return newString;
}
and the getCharIndexFirst() just returns the index of first occurance of the specified char the getCharIndexLast() just returns the index of last occurance of the specified char
and below is the main function:
//consoleCommand has the form of 'send MESSAGE ID', has the value from stdin
int firstSpace = getCharIndexFirst(consoleCommand,' ');
int lastSpace = getCharIndexLast(consoleCommand,' ');
int len = strlen(consoleCommand);
char *header = substring(consoleCommand,0,firstSpace);
printf("header is: %s\n",header);
char *cmd = substring(consoleCommand,firstSpace+1,lastSpace-firstSpace-1);
printf("command is: %s\n",cmd); // the code only runs up to here and output the error..
char *socketstr = substring(consoleCommand,lastSpace+1,len-lastSpace-1);
printf("socket is: %s\n",socketstr);
Here is more info: the consoleCommand is usually the stdin, has the form of 'send MESSAGE ID', the error occurs when the MESSAGE is 12 char long... e.g. 'send this message 4', 'this message' is the cmd and has length of 12 chars, this gives me error! and it works fine for any other lengths, i have tried 3, 4, 24...
Any hint will be appreciated, THANKS!
newString[x] = '\0';
At this point x
is equal to length
, which means you're writing 1 character beyond the end of the memory you allocated. You need to allocate space for one more character.
You don't allocate any space for the terminating '\0'
character, so you overflow your allocation to write this character. You need to count this character in your allocation too:
char *newString = (char *)malloc((length + 1) * sizeof(char));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With