为什么动态分配后我的指针数组会被覆盖?

时间:2013-08-17 22:33:44

标签: c pointers dynamic malloc allocation

我正在为一个类读取一个C语言程序,该类从文件中读取行,然后使用qsort对它们进行排序。简而言之,我正在为char*数组中存储为char*的文件的每一行动态分配内存。读取和存储表面上可以根据输出(见下文)正常工作,但是当我打印出行时,它们都是文件中最后一行的副本。任何人都可以指出我的(很可能是非常明显的)错误吗?

以下是我目前遇到的问题的相关代码:

char* trim_white_space(char* str);
char* get_line(FILE* infile, char temp[]);

int main(int argc, char* argv[]) {
    FILE* infile; 
    char* input_file = argv[1];
    int cnt = 0;
    char temp[MAX_LINE_LENGTH]; //to hold each line as it gets read in 
    char* tempPointer = temp;

    if (argc < 2) {
        printf("No input file provided");
        return EXIT_FAILURE;
    }

    //determine the number of lines in the file
    infile = fopen(input_file, "r");
    int num_lines_in_file = num_lines(infile);
    fclose(infile);

    //allocate pointers for each line
    char** lines = (char**) malloc(num_lines_in_file * sizeof(char*));

    //temporarily store each line, and then dynamically allocate exact memory for them
    infile = fopen(input_file, "r");
    for (cnt = 0; cnt != num_lines_in_file; cnt++) {
        tempPointer = get_line(infile, temp);  
        lines[cnt] = (char*) malloc(strlen(tempPointer) + 1);
        lines[cnt] = trim_white_space(tempPointer);
        printf("%d: %s\n", cnt, lines[cnt]);
    }

    fclose(infile);

    //print the unsorted lines (for debugging purposes)
    printf("Unsorted list:\n");
    for (cnt = 0; cnt != num_lines_in_file; cnt++) {
        printf("%s\n", lines[cnt]);
    }

char* get_line(FILE* infile, char temp[]) {
    fgets(temp, MAX_LINE_LENGTH-1, infile);
    char* pntr = temp;
    return pntr;
}

char *trimwhitespace(char *str)
{
  char *end;

  // Trim leading space
  while(isspace(*str)) str++;

  if(*str == 0)  // All spaces?
    return str;

  // Trim trailing space
  end = str + strlen(str) - 1;
  while(end > str && isspace(*end)) end--;

  // Write new null terminator
  *(end+1) = 0;

  return str;
}

我有这个示例输入文件5-1input.dat

Hi guys
x2 My name is
Slim Shady
For real

这是我得到的输出:

user@user-VirtualBox ~/Desktop/Low-level/HW5 $ ./homework5-1 5-1input.dat 
0: Hi guys
1: x2 My name is
2: Slim Shady
3: For real
Unsorted list:
For real
For real
For real
For real

1 个答案:

答案 0 :(得分:1)

与评论中一样,您应该将循环更改为:

for (cnt = 0; cnt != num_lines_in_file; cnt++) {
    tempPointer = get_line(infile, temp);  
    lines[cnt] = (char*) malloc(strlen(tempPointer) + 1);
    strncpy(lines[cnt], trim_white_space(tempPointer), strlen(tempPointer)+1);
    printf("%d: %s\n", cnt, lines[cnt]);
}

strncpy中的尺寸取决于您使用的malloc尺寸。

当然,您可以优化此代码,例如只计算一次strlen等等。