There is a fundamental problem with StrLeft, StrRight and StripWS
Neither strcpy, strncpy or memcpy are defined for overlapping memory.
That is, you can't rely on something like this always working.
Code:
char test[] = "hello world";
strcpy(test,test+2);
In all cases, the best thing to do is supply another parameter which points to a different area of memory.
char *StrLeft(char *out, const char str[],int count)
If the caller wants to copy the temporary buffer over the original source, then it's free to do so knowing that it's safe to do so.
Fixing split would be something like this.
Though perhaps you want split to be an output parameter, rather than local.
Code:
char *StrSplit(const char str[],int count){
char *split[2];
split[0]=StrLeft(str,count);
split[1]=StrRight(str,count);
printf("|%s|%s|\n",split[0],split[1]);
// you didn't malloc, so don't free(split);
return str;
}
> char **words=(char **)malloc(sizeof(char*)*lines_allocated);
Don't cast the result of malloc in a C program (see the FAQ).
If you've made the mistake of naming your source file as a .cpp file, you should correct this.
> new_size=lines_allocated+1; /* Add to allocation and re-allocate */
You're going to be calling realloc for every line you read, and this will be expensive.
Doing something like
new_size=lines_allocated * 2; /* Add to allocation and re-allocate */
If necessary, you can do one final realloc at the end to make the array of pointers the correct length.
> words=(char **)realloc(words,sizeof(char*)*new_size);
If realloc fails, then you've leaked all your memory. You should do this
Code:
void *temp = realloc(words,sizeof(char*)*new_size);
if ( temp ) {
words = temp;
} else {
// clean up words, or whatever
}
> if (fgets(words[i],max_line_len-1,fp)==NULL) break;
> for (j=strlen(words[i])-1;j>=0 && (words[i][j]=='\n' || words[i][j]=='\r');j--);//Strip CR+LF from end of line.
> words[i][j+1]='\0';
1. You don't need to subtract 1 from the buffer size passed to fgets
2. You won't normally see a \r in the buffer even on systems where \r\n is the line terminator, when the file is opened in text mode.
> (int)words[0]=i;
What a truly awful abuse of pointers.
Do something like this, and finish with
*numLinesRead = i;
char **FileReadArray(char File[], int *numLinesRead)
When you've fixed that, then you need to pass numLinesRead as a parameter to all your other functions, and you can start reading data[] from index 0, not index 1.