所以我用C语言编写了该程序,其想法是从3个文件中读取并显示其内容。它工作正常,但是用valgrind运行时出现错误。这是程序:
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <pthread.h>
struct structFile{
int numFile;
char* fileName;
};
void* fileThread(void* arg){
struct structFile* threadStruct = (struct structFile*) arg;
FILE *file = fopen(threadStruct->fileName, "r");`
char* charS = (char*) malloc(sizeof(char)*10);`
int sizeC = fread(charS, 1, 10, file);
while (sizeC < 10){
charS[sizeC] = ' ';
sizeC++;
}//while
fclose(file);
printf("%d. nit: %s\n", threadStruct->numFile, charS);
return charS;
}//fileThread
int main(int argc, char **argv){
pthread_t id[3];
char* word[3];
struct structFile* mainStruct = (struct structFile*) malloc (sizeof(struct structFile)*3);
for (size_t i = 0; i < 3; i++){
mainStruct[i].numFile = i;
mainStruct[i].fileName = (char*)argv[i+1];
pthread_create(&id[i], NULL, fileThread, mainStruct+i);
}//for
for (size_t i = 0; i < 3; i++){
pthread_join(id[i], (void**) &word[i]);
}//for
printf("Sporocilo-> %s %s %s\n", word[0], word[1], word[2]);
free(mainStruct);
free(word[0]);
free(word[1]);
free(word[2]);
return 0;
}//main
我真的不知道听到什么可能是错误的,有时它有时会显示7个错误4。我大约在1个月前开始使用c编程,所以它可能只是一个简单的答案,所以在此先感谢您的帮助。
问题是charS
没有空字节的空间(因为您想用%s
打印为字符串)。
分配一个额外的字节,并适当地将其终止,将其终止。
char *charS = malloc(10 + 1); // sizeof(char) can be omitted as it's always 1
int sizeC = fread(charS, 1, 10, file);
charS[sizeC] = '\0';
...
您还应该为fopen
,malloc
,pthread_create
等添加错误检查
读取10个字符,因此您需要为'\ 0'分配11个字符。像这样的Malloc:
char* charS = malloc(sizeof(char) * 11);`