我对 C 很陌生,似乎无法弄清楚以下代码有什么问题。
int main() {
char filen[] = "file.txt";
FILE *file = fopen ( filen, "r" );
if ( file != NULL )
{
char line [ 128 ];
while ( fgets ( line, sizeof line, file ) != NULL ) /* read a line */
{
int i;
char *result;
for(i=0; i< NUM;i++)
{
char *rep;
rep = (char *) malloc (sizeof(mychars[i][0]));
strcpy(rep, mychars[i][0]);
char *with;
with = (char *) malloc (sizeof(mychars[i][1]));
strcpy(with, cgichars[i][1]);
result = (char *) malloc (sizeof(char) * 128);
result = str_replace(line, rep, with);
}
fputs(result, stdout);
}
}
fclose ( file );
return 0;
}
Valgrind 给了我这个错误:
==4266== Invalid read of size 1
==4266== at 0x4C286D2: __GI_strlen (mc_replace_strmem.c:284)
==4266== by 0x5118A8D: fputs (iofputs.c:37)
==4266== by 0x400A0F: main (repl.c:35)
==4266== Address 0x0 is not stack'd, malloc'd or (recently) free'd
repl.c 对应于代码末尾以 fputs 开头的行。
此外,mychars 是一个二维数组,如下所示:
char *mychars[NUM][2] = {
"a", "97",
"b", "98",
....
有人可以告诉我如何解决这个问题吗?此外,任何关于我应该如何改进我当前代码(尤其是使用 malloc)的指针都将不胜感激。
编辑: str_replace 的代码
char *str_replace(char *str, char *orig, char *rep) {
char buffer[4096];
char *p;
if(!(p = strstr(str, orig)))
return NULL;
strncpy(buffer, str, p-str);
buffer[p-str] = '\0';
sprintf(buffer+(p-str), "%s%s", rep, p+strlen(orig));
return buffer;
}
编辑 2 str_replace 和 main 的新代码
出于测试目的,我将 str_replace 方法替换为此处的方法:
我的主要内容略有变化:
int main() {
static const char filen[] = "file.txt";
FILE *file = fopen ( filen, "r" );
if ( file != NULL )
{
char line [ 128 ];
while ( fgets ( line, sizeof line, file ) != NULL ) /* read a line */
{
int i;
char *result;
for(i=0; i< NUM;i++)
{
char *rep;
rep = (char *) malloc (sizeof(mychars[i][0]));
strcpy(rep, mychars[i][0]);
char *with;
with = (char *) malloc (sizeof(mychars[i][1]));
strcpy(with, mychars[i][1]);
result = str_replace(line, rep, with);
}
fputs(result, stdout);
}
}
fclose ( file );
return 0;
}
但我仍然得到
==6730== Invalid read of size 1
==6730== at 0x4C286D2: __GI_strlen (mc_replace_strmem.c:284)
==6730== by 0x5118A8D: fputs (iofputs.c:37)
==6730== by 0x400995: main (repl.c:29)
==6730== Address 0x0 is not stack'd, malloc'd or (recently) free'd
也许最令人沮丧的部分是不知道这些无效读取错误是什么。
编辑 3 我已经更新了 for 循环中心的代码,如下所示:
int i;
char* result;
result = &line[0];
for(i=0; i< NUM_CGICHARS;i++)
{
char *rep;
rep = (char *) malloc (sizeof(char));
strcpy(rep, cgichars[i][1]);
char *with;
with = (char *) malloc (sizeof(char)*3);
strcpy(with, cgichars[i][0]);
result = str_replace(result, rep, with);
fputs(result, stdout);
free(rep);
free(with);
}
现在我开始得到输出了!然而,仅在两次迭代之后,我得到了一个分段错误,而 valgrind 给了我一大堆这个:
==9130== Invalid read of size 1
==9130== at 0x4C286D2: __GI_strlen (mc_replace_strmem.c:284)
==9130== by 0x5118A8D: fputs (iofputs.c:37)
==9130== by 0x4009DF: main (teststep1.c:27)
==9130== Address 0x0 is not stack'd, malloc'd or (recently) free'd