c-geting free():执行代码时大小无效



用gcc hw2.c-o x-lpthread 编译

free(): invalid size
free(): invalid size
free(): invalid size
nano infile.txt

我想这可能和文件指针有关吧?信号量已被注释掉,以便首先解决此问题。所有的答案都指向指针,但改变方向并没有多大帮助。我尝试过以不同的方式编译,但也无济于事。

#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>
#include <semaphore.h>
#include <fcntl.h>
#include <sys/stat.h>
//sem_t X;
void process(){
//sem_open("X", O_CREAT,0777,0);
int ret;
int N = 1;
pid_t pid;
FILE* infile = fopen ("infile.txt", "r");
for(int i = 0; i< 50; i++){
fscanf (infile, "%d", &N);
fclose (infile);
printf("N: %d Process ID: %d",N,pid);
infile = fopen("infile.txt", "w");
N++;
//sem_post(&X);
fprintf(infile,"%d",N);
fflush(infile);
fclose(infile);
}
printf("n");
int c;
//sem_getvalue(&X,&c);
printf(" n n n%d",c);
}
int main(){
int pid, pid1, pid2;
pid = fork();
if(pid == 0){
//child1, Last
printf("Starting Process C: ");
process();
}
else{
pid1 = fork();
if(pid1 == 0){
//child2, Middle
printf("Starting Process B: ");
process();
}
else{
pid2 = fork();
if(pid2 == 0){
//child 3, First
printf("Starting Process A: ");
process();
}
else{
}
}

}
//sem_close(&X);
//sem_unlink(&X);
}

最明显的问题是在循环中。除了fopenfclose调用之外,我已经删除了所有内容:

FILE* infile = fopen ("infile.txt", "r");
for(int i = 0; i< 50; i++){
fclose (infile);
infile = fopen("infile.txt", "w");
fclose(infile);
}

正如您现在可能看到的,当i1时,您尝试fclose(infile),但它没有打开,因此会出现错误。

您需要将第一个fopen移动到循环中,并检查打开文件并从中读取是否也成功:

#include <fcntl.h>
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <sys/wait.h>
void process() {
int N = 1;
for(int i = 0; i < 50; i++) {
FILE* infile = fopen("infile.txt", "r");
if(infile) {
bool readok = fscanf(infile, "%d", &N) == 1;
fclose(infile);
if(readok) { /* only do this if a value was read from the file ok */
printf("N: %d Process ID: %d", N, getpid());
infile = fopen("infile.txt", "w");
if(infile) {
N++;
fprintf(infile, "%d", N);
fflush(infile);
fclose(infile);
}
}
}
}
printf("n");
exit(0); /* terminate this sub process */
}
int main() {
const size_t kPids = 3;
pid_t pids[kPids]; /* simplify keeping a number of background processes */
for(size_t i = 0; i < kPids; ++i) {
pids[i] = fork();
if(pids[i] == 0) {
printf("Starting Process %c:n", (char)('A' + i));
process();
}
}
/* wait for children to finish */
pid_t pid;
int wstatus;
while((pid = wait(&wstatus)) != -1) {
printf("pid %d is done with status %dn", pid, wstatus);
}
}

您的循环存在问题

FILE* infile = fopen ("infile.txt", "r"); //1
for(int i = 0; i< 50; i++){
fscanf (infile, "%d", &N);
fclose (infile); //2
printf("N: %d Process ID: %d",N,pid);
infile = fopen("infile.txt", "w"); //3
N++;
//sem_post(&X);
fprintf(infile,"%d",N);
fflush(infile);
fclose(infile); //4
}

1处打开文件,然后进入循环,在2处关闭,在3处重新打开,然后在4处重新关闭。在下一次迭代中,当你试图在2关闭时,你会遇到一个双自由,因为它已经在4关闭了。

最新更新