I made an attempt to shorten my code in a particular function because it had lines that repeated themselves.
The function that has duplicate lines but works
Code:
static Line newLines (char text[]) {
Line list = NULL, curr;
int lineCount = 1;
int length = strlen(text);
int subLength;
int i=0, prevPos = i;
if (*text == '\0')
return NULL;
list = malloc(sizeof(struct line));
if (list == NULL)
memoryError();
curr = list;
for (; i<length; i++) {
if (text[i] == '\n') {
//line text:
subLength = i-prevPos+1; //+1 = null terminator
curr->text = malloc(sizeof(char)*subLength);
if (curr->text == NULL)
memoryError();
strncpy(curr->text, &text[prevPos], subLength);
curr->text[subLength-1] = '\0';
//line number:
curr->lineNum = lineCount;
//next line:
curr->next = malloc(sizeof(struct line));
if (curr->next == NULL)
memoryError();
curr = curr->next;
prevPos = i+1;
lineCount++;
}
}
//line text:
subLength = i-prevPos+1;
curr->text = malloc(sizeof(char)*subLength);
if (curr->text == NULL)
memoryError();
strncpy(curr->text, &text[prevPos], subLength);
//line number:
curr->lineNum = lineCount;
//next line:
curr->next = NULL;
return list;
}
Notice that the first few lines in the for loop are equivalent to the bottom of the function.
Now, this is what I did to try and simplify things:
Code:
static Line newLines (char text[]) {
Line list = NULL, curr;
int lineCount = 1;
int length = strlen(text);
int subLength;
int i=0, prevPos = i;
if (*text == '\0')
return NULL;
list = malloc(sizeof(struct line));
if (list == NULL)
memoryError();
curr = list;
for (; i<=length; i++) {
if (text[i] == '\n' || text[i] == '\0') {
printf("text[i] = %c\n", text[i]);
//line text:
subLength = i-prevPos+1; // +1 = null terminator
curr->text = malloc(sizeof(char)*subLength);
if (curr->text == NULL)
memoryError();
strncpy(curr->text, &text[prevPos], subLength);
//line number:
curr->lineNum = lineCount;
//next line:
if (text[i] == '\n') {
curr->next = malloc(sizeof(struct line));
if (curr->next == NULL)
memoryError();
curr = curr->next;
prevPos = i+1;
lineCount++;
} else
curr->next = NULL;
}
}
return list;
}
And I just cannot figure out why it doesn't work. It works fine for single line text (no \n chars) but gives me some crazy memory error for multiple line text.
Could someone please give me a little insight into this?