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

calloc vs memset one shows resulzs and one doesn't

所以我想深入了解 C,以下是处理内存分配、文件和 strings/pointers 的代码。我已经尝试过使用 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], 0 ,LOG_MIN_FILENAME_SIZE + 2);
 }

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

这是有问题的:

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

memset 期望它的第一个参数是指向它将修改的缓冲区的指针。但是ListOfFiles[0]就是NULL[1]。没有什么好结果。具体来说,它是导致现代通用计算机上的 SIGSEGV(崩溃)的未定义行为。

另一方面,

calloc 分配一个缓冲区和 returns 指向它的指针。这确实是正确的做法。


  1. 因为ListOfFiles是在静态存储中找到的,因为它是全局的。在其他情况下,它可能未初始化,这更糟糕。