【发布时间】:2016-03-25 00:51:35
【问题描述】:
我有一些代码,它获取一个文件,将每一行读入一个新的字符串数组(并向每个字符添加 128),然后将每个数组分配给一个指针数组,然后打印每个数组。尝试运行代码时,我收到一条错误消息,指出由于以下原因导致分段错误:
strlen () at ../sysdeps/x86_64/strlen.S:106
106 ../sysdeps/x86_64/strlen.S: No such file or directory.
但我实际上从未在我的代码中调用 strlen?
#include <stdio.h>
#include <assert.h>
#include <stdlib.h>
#define ROW 10
#define COL 40
#define ARGS 2
#define FLIP_VALUE 128
char** read_file (char* argv[], char **array_pointers);
char* new_array (void);
void print_strings (char** array_pointers);
int main(int argc, char* argv[])
{
char **array_pointers = NULL;
if (argc == ARGS)
{
array_pointers = read_file(&argv[1], array_pointers);
print_strings(array_pointers);
}
return 0;
}
char** read_file (char* argv[], char **array_pointers)
{
FILE* file_name;
int i = 0, j = 0;
char c;
char *temp_array;
array_pointers = malloc(sizeof(char*) * ROW);
file_name = fopen(argv[0], "r");
assert(file_name);
if (file_name) /* if file is not null */
{
while (c != EOF) /* while not equal to end of file */
{
for (j = 0; j < ROW; j++) /* for each row */
{
temp_array = new_array(); /* generate a new array for each new string (row) */
for (i = 0; i < COL; i++) /* for each char in a row */
{
c = fgetc(file_name);
temp_array[i] = c + FLIP_VALUE;
}
array_pointers[j] = temp_array; /*assign array pointers to point at each new temp_array */
}
}
}
return array_pointers;
}
char* new_array (void)
{
char* temp;
temp = malloc(sizeof(char) * COL);
assert(temp);
return temp;
}
void print_strings (char** array_pointers)
{
int i = 0;
for (i = 0; i < COL; i++)
{
printf("%s\n",array_pointers[i]);
}
}
完整的堆栈跟踪如下:
#1 0x00007ffff7a84e3c in _IO_puts (str=0x0) at ioputs.c:36
result = -1
len = <optimised out>
#2 0x0000000000400806 in print_strings (array_pointers=0x602010)
at array_of_string_arrays.c:65
i = 10
#3 0x00000000004006a1 in main (argc=2, argv=0x7fffffffdff8)
at array_of_string_arrays.c:19
array_pointers = 0x602010
【问题讨论】:
-
建议您在调试器中运行您的程序并至少获得完整的堆栈跟踪。
-
c应该是int,否则while (c != EOF)永远不会是false。您还将为每个char创建一个新数组,而不是为每个新字符串。 -
看起来你在 for 循环中的条件只需要
j < ROW和i < COL -
您的
while (c != EOF)循环错误。见stackoverflow.com/questions/5431941/… -
将
128添加到字符串中的每个char然后尝试使用"%s"打印它不会打印出可读的内容。
标签: c arrays string segmentation-fault strlen