In the following code I call the editorOpen
method with a file name.
It always makes a segmentation fault except for when I comment out the first line in editorUpdateRow
(std::string rowStr(row);
).
Can someone explain why that happens?
void editorUpdateRow(const std::string& row)
{
std::string rowStr(row);
size_t index = 0;
while (index != std::string::npos)
{
index = rowStr.find("\t", index);
if (index != std::string::npos)
{
rowStr.replace(index, 1, KILO_TAB);
index += sizeof(KILO_TAB) - 1;
}
}
}
void editorAppendRow(char* row, size_t len)
{
config.rows = static_cast<std::string*>(realloc(config.rows, sizeof(std::string) * (config.numRows + 1)));
KILO_SANITY(config.rows != nullptr, "Couldn't realloc rows array");
printf("%d\n", config.numRows);
config.rows[config.numRows] = row;
printf("%d\n", __LINE__);
config.rows[config.numRows][len] = '\0';
printf("%d\n", __LINE__);
editorUpdateRow(config.rows[config.numRows]);
++config.numRows;
}
void editorOpen(char* filename)
{
KILO_SANITY(filename != nullptr, "Filename is NULL!!!");
FILE* fp = fopen(filename, "r");
KILO_SANITY(fp, "Open of %s Failed!!!", filename);
char* line = nullptr;
size_t linecap = 0;
ssize_t linelen = 0;
while((linelen = getline(&line, &linecap, fp)) != -1)
{
while (linelen > 0 && (line[linelen - 1] == '\n' ||
line[linelen - 1] == '\r'))
{
--linelen;
}
editorAppendRow(line, linelen);
}
free(line);
fclose(fp);
}