【发布时间】:2010-11-18 19:39:34
【问题描述】:
这比我之前的 Valgrind 问题更集中;我试图在解析命令行选项时缩小写入和读取错误的范围:
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/utsname.h>
#include <sys/stat.h>
#include <string.h>
#include <locale.h>
#include <bzlib.h>
#include <zlib.h>
#include "starch.h"
#define BUFMAXLEN 1024
int main(int argc, char **argv) {
if (parseCommandLineInputs( &argc, &argv ) != 0)
exit(EXIT_FAILURE);
return 0;
}
int parseCommandLineInputs(int *argc, char ***argv) {
pid_t pid;
struct utsname uts;
char uniqTag[BUFMAXLEN];
if ((*argc == 1) || (*argc > 4)) {
printUsage();
return -1;
}
if ((pid = getpid()) < 0) {
fprintf(stderr, "\n\t[starch] - Error: Could not obtain process ID\n\n");
return -1;
}
uname( &uts );
sprintf(uniqTag, "pid%d.%s", pid, uts.nodename);
switch (*argc) {
case 2: {
if (strcmp(*argv[1], "-") != 0) {
if (fileExists(*argv[1]) != 0) { /* standard input */
...
}
return 0;
}
int fileExists(char *fn) {
struct stat buf;
int i = stat (fn, &buf);
if (i == 0)
return 0;
return -1;
}
void printUsage() {
fprintf(stderr, "my usage statement\n\n");
}
我的makefile如下:
CC = gcc
CFLAGS = -D_FILE_OFFSET_BITS=64 -D_LARGEFILE64_SOURCE=1 -DUSE_ZLIB -O3 -Wformat -Wall -pedantic -std=gnu99 -g
BIN = ../bin
all: starch
rm -rf *~
starch: starch.o
mkdir -p $(BIN) && $(CC) ${CFLAGS} starch.o -lbz2 -lz -o ${BIN}/starch
rm -rf *~
clean:
rm -rf *.o *~ ${BIN}/starch
当我使用valgrind 运行时出现以下错误:
$ valgrind --tool=memcheck --leak-check=yes --show-reachable=yes --num-callers=20 --track-fds=yes -v ../bin/starch
...
==2675== 1 errors in context 1 of 2:
==2675== Invalid read of size 8
==2675== at 0x3AB4262243: fwrite (in /lib64/libc-2.5.so)
==2675== Address 0x7fedffd68 is on thread 1's stack
==2675==
==2675==
==2675== 1 errors in context 2 of 2:
==2675== Invalid write of size 8
==2675== at 0x401AA6: parseCommandLineInputs (starch.c:217)
==2675== by 0x7FF0000AF: ???
==2675== by 0x401DFA: main (starch.c:46)
==2675== Address 0x7fedffd68 is on thread 1's stack
第一个错误没有告诉我任何我可以使用的东西,因为我没有在任何地方使用fwrite()。
printUsage() 中的 fprintf 语句引发了第二个错误。
第 46 行是以下行:
if (parseCommandLineInputs( &argc, &argv ) != 0)
第 217 行是以下行:
fprintf(stderr, "my usage statement\n\n");
我的应用程序有什么问题可以解释为什么会出现这些错误?
【问题讨论】:
-
这不是完整的程序(没有
#includes,没有uts、uniqTag或pid的定义)。为什么parseCommandLineInputs中的行都是尾随空格? -
您希望我们如何只用一半的信息调试您的程序? uts, uniqTag 在哪里?淀粉.c 的第 46 行和第 217 行是什么?你试过使用 --db-attach=yes 吗?