typedef struct textNode{ //basically contains a line + link
char* line;
int sLength; //length of string
struct textNode* next;
} tNode;
struct textbuffer{
int size; //number of lines in the text buffer
int totalsLength;
tNode* head;
tNode* tail;
};
char *dumpTB (TB tb){
int stringLength = tb->totalsLength; //sLength is
char* text = malloc(sizeof(char) * stringLength+1);
int i = 0;
int x = 0; //string index
tNode* curr = tb->head;
while(curr != NULL){
while(curr->line[x] != '\n'){
printf("%d", i);
text[i] = curr->line[x];
printf("%c\n", text[i]);
i++;
x++;
}
printf("%d\n", i);
text[i] = '\n';
printf("%c", text[i]);
i++;
x = 0;
curr = curr->next;
}
text[tb->totalsLength] = '\0';
return text;
}
所以我在我的代码中有print语句,我在dumpTB中进行了malloced,它似乎在那里抛出了一个sysmalloc断言失败并中止了我的程序。不能为我的生活弄清楚为什么...我打印出数字totalsLength及其36,这是textBuffer中字符串的长度,我验证是正确的。谁能告诉我这是什么问题?
编辑:请求新代码
static tNode* newTN(char* string, int sLength, tNode* next){
tNode* t = malloc(sizeof(struct textNode));
t->line = malloc(sizeof(char)*sLength);
if(string != NULL){
strcpy(t->line, string);
}
t->next = next;
return t;
}
TB newTB (char text[]){
assert(text != NULL);
int i = 0;
char c;
TB tBuffer = malloc(sizeof(struct textbuffer));
tBuffer->size = 0;
//tNode* currLine = malloc(sizeof (struct textNode*));
tNode* currLine = newTN(NULL, 1, NULL);
tNode* currtNode = NULL;
//currLine->line = malloc(sizeof(char));
while(1){
c = text[i];
if(c == '\0'){
break;
} else{
currLine->line = realloc(currLine->line, currLine->sLength+1);
}
currLine->line[currLine->sLength] = c;
if(c == '\n'){ // create new textNode to contain string
if(tBuffer->size == 0){
tBuffer->head = newTN(currLine->line, currLine->sLength, NULL);
currtNode = tBuffer->head;
} else{
currtNode->next = newTN(currLine->line, currLine->sLength, NULL);
tBuffer->tail = currtNode->next;
currtNode = currtNode->next;
}
tBuffer->totalsLength += currLine->sLength+1; //account for \n
currLine->line = realloc(currLine->line, 0);
currLine->sLength = 0;
tBuffer->size++;
i++;
continue;
}
currLine->sLength++;
i++;
}
free(currLine->line);
free(currLine);
//printBuffer(tBuffer);
return tBuffer;
}
编辑:添加主要
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "textbuffer.h"
int main(int argc, char *argv[]) {
TB tb1 = newTB("HI\nHIYO\nHELLO\nwut\nyolo\nugnad\n");
//swapTB(tb1, 0, 5);
char* text = dumpTB(tb1);
int i = 0;
while(text[i] != 'd'){
printf("%c", text[i]);
i++;
}
printf("\n");
releaseTB(tb1);
return EXIT_SUCCESS;
}
char* text = malloc(sizeof(char) * stringLength+1);
好的,所以text
有stringLength + 1
可访问的字节。
text[i] = '\n';
如果且仅当i
小于或等于stringLength
时,这是合法的。所以我们在它之前添加一些代码:
if (i > stringLength)
printf("ACCESS OUT OF BOUNDS: i=%d stringLength=%d\n", i, stringLength);
现在让我们编译并运行它:
三十 进入界限:i = 30 stringLength = 29 31 进入界限:i = 31 stringLength = 29 32 访问界限:i = 32 stringLength = 29 33 进入界限:i = 33 stringLength = 29 ...
休斯顿,我们有一个问题。