calloc vs memset一个显示结果,一个不显示

问题描述

因此,我试图深入了解C,以下是处理内存分配,文件和字符串/指针的代码。我已经尝试过使用callocate和memset。 callocate似乎工作正常,但memset却不行。 代码的想法如下:我创建了一些文件,每次创建文件时,其名称就会被推送到列表中。我要保留固定数量文件。并在该编号显示后,每次创建新文件时都会删除最旧的文件。 使用 calloc 时。打印件会显示正确的消息,并且我的文件夹中包含最近的文件数: 这是代码

#include <stdio.h>
#include <stdlib.h>   // needed for malloc
#include <string.h>   // needed for strcpy
#include <unistd.h>

#define  Extension                         ".txt"
#define LOG_MIN_FILENAME_SIZE               32
#define  NBR_OF_FILES                        6

char buffer[LOG_MIN_FILENAME_SIZE];   
                                     
int timez = 0;
int minutes = 0;
int NUM_OF_EXISTING_FILES=0;


FILE *pf = NULL;
char* listofFiles[NBR_OF_FILES];
int status;



int main(void){
    
 for(int i=0; i<NBR_OF_FILES;i++){

listofFiles[i] = calloc(LOG_MIN_FILENAME_SIZE + 1,1);




  for(int i=0; i<10;i++) { 
  
  
    pf =fopen(buffer,"w");
    sprintf(buffer,"%d""%d"Extension,minutes,timez);
    
    if(access(buffer,F_OK)==-1){
        
        NUM_OF_EXISTING_FILES++;
        fclose(pf); //closing the files is necessary
        if(NUM_OF_EXISTING_FILES >= NBR_OF_FILES){
                status = remove(listofFiles[0]);
                printf("removed");  
                }
        
        
        for(int i=0; i < NBR_OF_FILES-1; i++){
                strcpy(listofFiles[i],listofFiles[i+1]);// u cant use just normal assignment because it copies the head ot the pointer rather than the actual content of it
        }
    
        strcpy(listofFiles[NBR_OF_FILES-1],buffer);
    }
        
    timez++;
    minutes++;
    
    }
    
    for(int i=0; i<NBR_OF_FILES-1; i++){
        printf("%s",listofFiles[i]);
    }
}

现在上面的代码按我所说的工作,但是一旦我用以下代码替换calloc行:

    (void) memset(listofFiles[i],LOG_MIN_FILENAME_SIZE + 2);
 }

代码不显示任何内容,也没有创建文件 memset calloc 有什么区别?为什么它对我不起作用?

解决方法

这是有问题的:

char* ListOfFiles[NBR_OF_FILES];
memset(ListOfFiles[0],...);

memset期望其第一个参数是指向将要修改的缓冲区的指针。但是ListOfFiles[0]NULL [1] 。没有任何好处。特别是,这种不确定的行为会导致现代通用计算机上发生SIGSEGV(崩溃)。

另一方面,

calloc分配一个缓冲区并返回指向它的指针。这确实是正确的方法。


  1. 因为ListOfFiles是静态存储,因为它是全局存储。在其他情况下,它可能未初始化,甚至更糟。