Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

glibc detected malloc(): memory corruption in C

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!

like image 601
Hugh H Avatar asked Sep 27 '13 17:09

Hugh H


2 Answers

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.

like image 146
Katniss Avatar answered Nov 17 '22 03:11

Katniss


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));
like image 43
cdhowie Avatar answered Nov 17 '22 04:11

cdhowie