Article 6FNMJ C - assert fails on 2nd run of same function.

C - assert fails on 2nd run of same function.

by
jmgibson1981
from LinuxQuestions.org on (#6FNMJ)
Function in question.

Code:void file_reverse_output(FILE * file,
FILE * newfile,
char * type)
{
// we don't check newfile as NULL is a valid value
assert(file);

// declare & initialize
long int len = file_num_lines(file);
long int maxstr = 0;

if (string_is_valid(type, "memsave")) {
maxstr = file_longest_string(file);
printf("memsave active\n");
} else if (string_is_valid(type, "nomemsave")) {
// this section fails assertion on file at getline_mem_alloc
// below
maxstr = MAX_BUFFER;
printf("standard buffer active\n");
} else {
printf("specify memsave / nomemsave\n");
exit(1);
}

char buffer[len][maxstr + 1];
// initialize array. this solved an uninitialized value
// error in valgrind down in the print loop. there may
// be a better way to solve the error. this isn't the
// fastest i'm guessing
for (int i = 0; i <= len; i++) {
for (int j = 0; j <= maxstr; j++) {
buffer[i][j] = '\0';
}
}

// loop through each line in text file, put in buffer for
// future stdout / fprintf
for (int i = 0; i < len; i++) {
char * ptr = getline_mem_alloc(file);
if (!ptr) {
break;
}
// load lines into buffer and clear pointer
strncpy(buffer[i],
ptr,
maxstr - 1);
clear_char_ptr(ptr);
}

// reset file for next usage
rewind(file);

// print buffer in reverse order to either stdout or newfile
for (int j = len - 1; j >= 0; j--) {
no_more_newline(buffer[j]);
if (newfile == NULL) {
printf("%s\n",
buffer[j]);
} else {
fprintf(newfile,
"%s\n",
buffer[j]);
}
}

// rewind temp for next usage
if (newfile) {
rewind(newfile);
}
}I started screwing around with minimizing memory usage. Not fast but keeps the buffer only as big as it needs to be. My problem is when I run it from this test.c file.

Code:#include <stdio.h>
#include <jmgeneral.h>
#include <string.h>

int main()
{
FILE * file = fopen("testfile.txt", "r");
if (!file) {
printf("failed to open\n");
return(1);
}
// this one works fine
file_reverse_output(file, NULL, "memsave");
// this run fails file assertion when it gets to
// getline function in file_reverse_output
file_reverse_output(file, NULL, "nomemsave");
fclose(file);
file = NULL;
return(0);
}I can't figure why it works the first time then falls over the 2nd.

GIT - https://gitlab.com/jmgibson1981/mylibraries
External Content
Source RSS or Atom Feed
Feed Location https://feeds.feedburner.com/linuxquestions/latest
Feed Title LinuxQuestions.org
Feed Link https://www.linuxquestions.org/questions/
Reply 0 comments