I am trying to compile and code written in C under linux and received this error message: glibc detected malloc (): memory corruption, and I cannot understand why ...
substring () will simply return you part of the original string, specifying the starting index and length. for example a substring ("this is an 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 getCharIndexFirst () just returns the index of the first event of the specified char getCharIndexLast () just returns the index of the last visibility of the specified char
and below - 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 additional information: consoleCommand is usually stdin, it has the form "Send MESSAGE ID", an error occurs when the message MESSAGE is 12 char long ... for example, 'send this message 4', 'this message' is cmd and has a length of 12 characters, it gives me an error! and it works great for any other length, I tried 3, 4, 24 ...
Any hint would be appreciated, THANKS!