Glibc detected by malloc (): memory corruption in C

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!

+6
source share
2 answers
 newString[x] = '\0'; 

At this point, x is equal to length , which means that you are writing 1 character outside of the allocated memory. You must make room for another character.

+12
source

You do not allocate space for the trailing '\0' character, so you overflow your selection for writing this character. You should also count this symbol in your distribution:

 char *newString = (char *)malloc((length + 1) * sizeof(char)); 
+5
source

Source: https://habr.com/ru/post/954801/


All Articles