Skip to content

Commit

Permalink
Merge pull request #1418 from k-takata/fix-internal-sort
Browse files Browse the repository at this point in the history
main: Replace last '\n' with '\0' before sorting (Fix #1411)
  • Loading branch information
k-takata authored May 28, 2017
2 parents 8957fe3 + cbdcc66 commit 576f054
Showing 1 changed file with 13 additions and 3 deletions.
16 changes: 13 additions & 3 deletions main/sort.c
Original file line number Diff line number Diff line change
Expand Up @@ -193,7 +193,7 @@ static int compareTags (const void *const one, const void *const two)
}

static void writeSortedTags (
char **const table, const size_t numTags, const bool toStdout)
char **const table, const size_t numTags, const bool toStdout, bool newlineReplaced)
{
MIO *mio;
size_t i;
Expand All @@ -214,8 +214,12 @@ static void writeSortedTags (
* pattern) if this is not an xref file.
*/
if (i == 0 || Option.xref || strcmp (table [i], table [i-1]) != 0)
{
if (mio_puts (mio, table [i]) == EOF)
failedSort (mio, NULL);
else if (newlineReplaced)
mio_putc (mio, '\n');
}
}
if (toStdout)
mio_flush (mio);
Expand All @@ -228,11 +232,12 @@ extern void internalSortTags (const bool toStdout, MIO* mio, size_t numTags)
const char *line;
size_t i;
int (*cmpFunc)(const void *, const void *);
bool newlineReplaced = false;

/* Allocate a table of line pointers to be sorted.
*/
const size_t tableSize = numTags * sizeof (char *);
char **const table = (char **) malloc (tableSize); /* line pointers */
char **table = (char **) malloc (tableSize); /* line pointers */
DebugStatement ( size_t mallocSize = tableSize; ) /* cumulative total */


Expand Down Expand Up @@ -260,6 +265,11 @@ extern void internalSortTags (const bool toStdout, MIO* mio, size_t numTags)
failedSort (mio, "out of memory");
DebugStatement ( mallocSize += stringSize; )
strcpy (table [i], line);
if (table[i][stringSize - 2] == '\n')
{
table[i][stringSize - 2] = '\0';
newlineReplaced = true;
}
++i;
}
}
Expand All @@ -270,7 +280,7 @@ extern void internalSortTags (const bool toStdout, MIO* mio, size_t numTags)
*/
qsort (table, numTags, sizeof (*table), cmpFunc);

writeSortedTags (table, numTags, toStdout);
writeSortedTags (table, numTags, toStdout, newlineReplaced);

PrintStatus (("sort memory: %ld bytes\n", (long) mallocSize));
for (i = 0 ; i < numTags ; ++i)
Expand Down

0 comments on commit 576f054

Please sign in to comment.