【发布时间】:2015-06-27 06:32:46
【问题描述】:
我知道以前有人问过这个问题,并且我认为我理解有分段错误意味着我在某处有一个错误的指针。话虽如此,我非常感谢帮助我找出我的错误所在。我有一个头文件和两个源文件,它们是
标题:
#ifndef LINEHOLDER_H_INCLUDED
#define LINEHOLDER_H_INCLUDED
#define DEFAULT 100
#define MAXLEN 256
#define MAXLINES 1024
int readlines(char *lineptr[], int maxlines);
unsigned getline2(char *s, int size);
void printlines(char **lineptr, int size, int numlines);
#endif // LINEHOLDER_H_INCLUDED
第一个源文件是:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include "lineholder.h"
int main(int argc, char *argv[])
{
char *lineptr[MAXLEN]; /* input lines */
int linecount = 0;
int tail_count = 0;
int i;
for (i = 1 ; i < argc ; ++i)
{
char *arg = argv[i];
if (strcmp(arg, "-n") == 0);
{
char *endptr;
tail_count = strtol(arg, &endptr, 10);
if (*endptr == '\0')
continue;
fprintf(stderr, "warning , argument `%d' is not an integer\n", 1 + i);
}
}
if (!tail_count)
tail_count = 10;
if ((linecount = readlines(lineptr,MAXLINES)) >= 0)
printlines(lineptr, linecount,tail_count);
return 0;
}
第二个源文件是:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include "lineholder.h"
unsigned getline2(char *s, int size);
int readlines(char *lineptr[], int maxlines)
{
int len, nlines;
char *p, line[MAXLEN];
nlines = 0;
while ((len = getline2(line, MAXLEN)) > 0) {
p = malloc(len);
if (nlines >= maxlines || p == NULL) {
return -1;
} else {
// line[len-1] = '\n';
if ((len > 0) && line[len-1] == '\n') line[len-1] = '\n';
strcpy(p,line);
lineptr[nlines++] = p;
}
}
return nlines;
}
void printlines(char **lineptr, int size, int numlines)
{
/* 72 lines, we start on line 62 */
int print_start;
int line;
print_start = size - numlines;
for (line=print_start; line < size; line++)
printf("%s", lineptr[line]);
}
unsigned getline2(char *s, int size)
{
int i, c;
for (i=0; i<size-1 && (c=getchar()) != EOF && c != '\n'; ++i)
*s++ = c;
if (c == '\n') {
*s++ = c;
++i;
}
*s = '\0';
return i;
}
使用 makefile 构建它后,我将获得一个名为 tails 的可执行文件 当我运行 ./tails test.out 时,我收到分段错误核心转储错误。谁能帮我弄清楚我想在哪里分配我不应该分配的内存?
谢谢
感谢你们的帮助,我更新了代码,但我的问题仍然存在。
【问题讨论】:
-
您可能存在内存泄漏。如果在
readlines函数中读取一行,分配内存,然后表达式nlines >= maxlines为真,该怎么办? -
0)
int tail_count;应该是int tail_count=0; -
1)
char *lineptr[MAXLEN];,readlines(lineptr,MAXLINES)大小不匹配。
标签: c