为什么没有将内存正确分配给C中的char *?

时间:2017-03-02 22:54:11

标签: c multithreading memory

说实话,我不知道该写什么作为标题。我面临的问题是,一旦我将内存分配给LinkedList结构中的char *行,它在下一次迭代中似乎缩小到26。我没有写完整的代码(只有我认为相关的部分)。 fileRead_runner是一个线程运行方法,它的作用是搜索具有特定关键字的行,并以链表的形式发送回父级。我打算用LinkedList结构中的char *行来做这件事,但我面临一些神秘的问题。我已经给出了样本输出。 “out:number”是字符串的实际大小,下一行的数字是程序存储的长度。

任何帮助将不胜感激! 谢谢!

struct LinkedList{
    char* line;
    struct LinkedList* next;
};
struct  Node{
    char *keyword;
    char* fileName;
    struct LinkedList* head;
};
    void* fileRead_runner(void* args){
        struct Node* node = (struct Node*)args;
        FILE* fp;
        char* out;
        node->head = malloc(sizeof(char*)+sizeof(struct LinkedList*));
        struct LinkedList* curr;
        curr = node->head;
        fp = fopen(node->fileName, "r");
        int lineNum = 1;
        char line[512];
        int found;
        int first = 0;
        while(fgets(line, sizeof(line), fp) != NULL){
            found = 0;
            char* temp = malloc(sizeof(line));
            strcpy(temp, line);
            char* token = strtok(temp, " \t\n");
            while(token != NULL && found == 0){
                if(strcmp(token, node->keyword) == 0){
                    found = 1;
                }
                token = strtok(NULL, " \t\n");
            }
            if(found == 1){
                out = malloc(sizeof(line));
                char* num = malloc(sizeof(char)*4);
                snprintf(num, sizeof(num), "%d: ", lineNum);
                strcpy(out, node->fileName);
                strcat(out, ", ");
                strcat(out, num);
                strcat(out, line);
                if(first != 0){
                    curr->next = malloc(sizeof(struct LinkedList*));
                    printf("%d\n", strlen(curr->line));
                    curr = curr->next;
                }
                curr->line = malloc(sizeof(out));
                strcpy(curr->line, out);
                first = 1;
                //curr->next = NULL;
                printf("out: %d\n", strlen(curr->line));
            }
            lineNum++;
        }
    }

输出:

out: 202
26
out: 18
18
out: 94
26
out: 155
26
out: 242
26
out: 96
26
out: 27
26
out: 133
26
out: 25
26
out: 93
26
out: 35

1 个答案:

答案 0 :(得分:2)

            curr->line = malloc(sizeof(out));

由于outchar *,因此为curr->line分配了一些字节,等于指针占用的字节数。这是没有意义的。也许你想要:

            curr->line = malloc(strlen(out) + 1);

这会分配足够的空间来存储字符串,并使用零字符来标记其结尾。