R
Ralph A. Moritz
Hi everyone,
first of all, sorry for using Google to post. I know
some people find this offensive, but as I am stuck
behind a firewall, I don't have a choice.
I am reading ``The Practice of Programming'' by
Kernighan & Pike, and I have cannibalized their csv
functions. I have added another function: csvmkline,
which constructs a csv format string from a
NULL-terminated string vector.
The problem is that I am getting a segmentation fault.
I've been debugging the function for about an hour
now, but I just can't see the darn bug(s)! Please
help!
Regards,
Ralph
static char *line;
static int maxline;
char *csvmkline(const char *fields[])
{
char *newl;
int i;
size_t len = 0;
maxline = 1;
line = malloc(maxline);
if (line == NULL) {
reset();
return NULL;
}
for (i = 0; fields != NULL; i++) {
size_t rlen = strlen(fields) + 1; /* required length */
int quote = needs_quotes(fields);
if (quote) {
rlen += 2;
}
if (maxline-len <= rlen) { /* grow buffer */
newl = realloc(line, maxline += rlen);
if (newl == NULL) {
reset();
return NULL;
}
line = newl;
}
if (len > 0) { /* do we need a comma? */
line[len++] = ',';
}
if (quote) { /* do we need to quote? */
line[len++] = '"';
}
newl = &line[len];
memmove(newl, fields, strlen(fields));
if (newl == NULL) {
reset();
return NULL;
}
len += strlen(fields);
if (quote) { /* close quotes */
line[len++] = '"';
}
}
line[len] = '\0';
return line;
}
first of all, sorry for using Google to post. I know
some people find this offensive, but as I am stuck
behind a firewall, I don't have a choice.
I am reading ``The Practice of Programming'' by
Kernighan & Pike, and I have cannibalized their csv
functions. I have added another function: csvmkline,
which constructs a csv format string from a
NULL-terminated string vector.
The problem is that I am getting a segmentation fault.
I've been debugging the function for about an hour
now, but I just can't see the darn bug(s)! Please
help!
Regards,
Ralph
static char *line;
static int maxline;
char *csvmkline(const char *fields[])
{
char *newl;
int i;
size_t len = 0;
maxline = 1;
line = malloc(maxline);
if (line == NULL) {
reset();
return NULL;
}
for (i = 0; fields != NULL; i++) {
size_t rlen = strlen(fields) + 1; /* required length */
int quote = needs_quotes(fields);
if (quote) {
rlen += 2;
}
if (maxline-len <= rlen) { /* grow buffer */
newl = realloc(line, maxline += rlen);
if (newl == NULL) {
reset();
return NULL;
}
line = newl;
}
if (len > 0) { /* do we need a comma? */
line[len++] = ',';
}
if (quote) { /* do we need to quote? */
line[len++] = '"';
}
newl = &line[len];
memmove(newl, fields, strlen(fields));
if (newl == NULL) {
reset();
return NULL;
}
len += strlen(fields);
if (quote) { /* close quotes */
line[len++] = '"';
}
}
line[len] = '\0';
return line;
}