gpt4 book ai didi

c - 当我用printf删除不相关的句子时,我的程序将无法正常运行

转载 作者:行者123 更新时间:2023-11-30 20:12:26 26 4
gpt4 key购买 nike

事实上,我已经快完成练习5-13了,但是出现了一个很奇怪的问题,我找不到我犯了什么错误:当我删除代码的第 13 行时,即printf("%d\n",argc);我的程序无法正常运行,并且遇到一个问题:当我输入 ./tail -10

#include <stdio.h>
#define MAXSIZE 1000

/* prints the last linesof its input,and the n's default value is 10 */
int main(int argc, char *argv[])
{
int atoi(char*);
int readlines(char *lineptr[], int maxlines);/* read the input to the lineptr */
int n = 10;
int i;
char *lineptr[MAXSIZE];/* store the the point of input lines */
int lines;
printf("%d\n",argc);
while(--argc > 0){
if((*++argv)[0] == '-') {
n = atoi(++*argv);
printf("%d\n",n);
}
else {
printf("Error input\n");
return -1;
}
}
lines = readlines(lineptr,MAXSIZE);// lines is the the actual lines of input */
if(lines > n) /* print ten the last n lines */
for(i = lines - n;i <= lines -1;i++)
printf("%s\n",lineptr[i]);
else
for(i=0;i < lines;i++) /* print all the input */
printf("%s\n",lineptr[i]);
return 0;
}

readline.c

#include <stdio.h>
#include <string.h>

#define MAXLEN 1000 /* max length of any input line */

int getLine(char *, int);
char *alloc(int);
/* readlines: read input lines */
int readlines(char *lineptr[], int maxlines)
{
int len,nlines;
char *p,line[MAXLEN];

while((len = getLine(line,MAXLEN)) > 0)
if(nlines >= maxlines || (p = alloc(len)) == NULL)
return -1;
else {
line[len-1] = '\0';
strcpy(p,line);
lineptr[nlines++] = p;
}
return nlines;
}

int getLine(char *s, int lim)
{
int i;
int c;
for(i = 0;i<lim-1 && (c=getchar())!=EOF && c != '\n';i++)
*s++ = c;
if(c=='\n') {
*s++ = c;
i++;
}
*s = '\0';
return i;
}

分配.c

#define ALLOCSIZE 10000

static char allocbuf[ALLOCSIZE];
static char *allocp = allocbuf;

char *alloc(int n)
{
if(allocbuf + ALLOCSIZE - allocp >=n) {
allocp += n;
return allocp -n;
}
else
return 0;
}

atoi.c

#include <ctype.h>

int atoi(char *p)
{
int sign,n;
int c;
while(isspace(*p))
p++;
if((c = (*p)) == '+' || c == '-')
p++;
sign = c == '-' ? -1 : 1;
for(n = 0;isdigit(c=*p);p++)
n = n * 10 + (c - '0');
return n * sign;
}

最佳答案

您在 readLines 中有一个未初始化的变量:

int len,nlines;       // nlines not initialized
char *p,line[MAXLEN];

while((len = getLine(line,MAXLEN)) > 0)
// nlines used here
if(nlines >= maxlines || (p = alloc(len)) == NULL)

未初始化的局部变量具有未定义的内容,因此尝试使用该值会导致 undefined behavior .

声明时需要设置nlines=0

我能够通过 valgrind 快速找到这个问题,这给了我以下输出:

==8219== Conditional jump or move depends on uninitialised value(s)
==8219== at 0x40076A: readlines (x1.c:48)
==8219== by 0x4006CE: main (x1.c:27)
==8219==
==8219== Use of uninitialised value of size 8
==8219== at 0x4007C2: readlines (x1.c:53)
==8219== by 0x4006CE: main (x1.c:27)
==8219==

关于c - 当我用printf删除不相关的句子时,我的程序将无法正常运行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35509790/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com