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("%cn", text[i]);
i++;
x++;
}
printf("%dn", i);
text[i] = 'n';
printf("%c", text[i]);
i++;
x = 0;
curr = curr->next;
}
text[tb->totalsLength] = ' ';
return text;
}
所以我在我的代码周围有印刷语句,在该代码中我在邓普(Dumptb)上杂乱无章,似乎在那里抛出了sysmalloc断言失败并中止了我的程序。我的一生无法确定原因...我打印了数字总计及其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 == ' '){
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("HInHIYOnHELLOnwutnyolonugnadn");
//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=%dn", i, stringLength);
现在让我们编译并运行它:
30
访问范围:i = 30 stringLength = 29
31
访问范围:i = 31 stringLength = 29
32
访问范围:i = 32 stringLength = 29
33
访问范围:i = 33 stringLength = 29
...
休斯顿,我们有问题。