c - 打印字符串数组行时出现段错误,逐个字符打印时工作正常

标签 c string segmentation-fault printf dynamic-arrays

我有这个代码:

char **data;
int start = 0;

data = malloc(all_names * sizeof(char*));

        fd=open(argv[1],O_RDWR|O_CREAT,S_IRWXU);
        for(i=0; i<all_names; i++){
            data[i] = malloc((MAX_SIZE+1)*sizeof(char));

            int end = atoi(positions[i]);
            lseek(fd,0,start);
            read(fd,data[i],(end-start));
            data[i][end - start] = 0; //line edited in after answer
            start = end;

        }

        qsort(data, all_names, sizeof(char*), strcmp);

        for(int i=0; i<all_names; ++i)
        {
            printf("%s\n", data[i]);
        }

        /*//print data array
        start = 0;
        for(i=0; i<all_names; i++){
            int end = atoi(positions[i]);
            for(j=0;j<(end-start) ;j++){
                printf("%c",data[i][j]);
            }
            printf("\n");
        }*/

运行它时我得到的是尝试打印时出现段错误。

如果我注释掉qsort和打印for,并在打印数据数组部分中进行注释,我会如预期的那样得到所有我的条目按照我插入的顺序排列。

如果我保留 qsort ,但保留 for 循环作为我的打印方法,我仍然会遇到段错误。

1.数据数组中的字符串来自文件,因此它们可能不是以 null 结尾的。但是,我对添加空字节犹豫不决,因为当我将排序后的数组写回到文件中时,它一定不存在

  • **positions 数组包含除第一个条目之外的每个条目的起点。例如。如果我插入“alpha一”然后插入“beta二”,则位置[0] = 9。
  • 请告诉我进一步解释任何我没有解释清楚的地方。谢谢。

    编辑:整个代码,因为事实证明我无法找到问题

    #include <stdio.h>
    #include <stdlib.h>
    #include <string.h>
    #include <unistd.h>
    #include <fcntl.h>
    
    #define MAX_SIZE 50
    
    int updateCounter(int pcounter, char *str){
    int m,charcount = 0;
    for(m=0; str[m]; m++) {
            charcount ++;
    }
    //charcount--;
    printf("chars: %d \n", charcount);
    
    pcounter = pcounter + charcount;
    printf("pcounter = %d \n", pcounter);
    
    return pcounter;
    }
    
    int main(int argc, char *argv[]){
    
    int option,i,j;
    FILE *fptr;
    char *name;
    int dcounter,pcounter = 0;
    int fd;
    char **positions,**data;
    int all_names=0; //keeps track of how many names are currently stored
    int start = 0; //first byte of word to read in data.bin
    char *filename = argv[2];
    
    name=(char*)malloc((MAX_SIZE+1)*sizeof(char));
    
    do{
        printf("MENU: \n 1.Insert \n 2.Delete \n 3.Search \n 4.Display \n");
    
    
        printf("Please choose 1-4\n");
        scanf("%d", &option);
        while(getchar() != '\n');
    
        //Insert
        if(option==1){
    
            printf("Insert name: ");
            fgets(name,MAX_SIZE,stdin);
            name[strcspn(name,"\n")]=0;
    
            fd=open(argv[1],O_RDWR|O_CREAT|O_APPEND,S_IRWXU);
            write(fd,name,strlen(name));
    
            pcounter = updateCounter(pcounter, name);
    
            char passpos[5];
            sprintf(passpos,"%d",pcounter); //int to string
            fd=open(argv[2],O_RDWR|O_CREAT|O_APPEND,S_IRWXU);
            write(fd,passpos,3);
            write(fd," ",1);
    
            all_names++;
            printf("all names: %d\n",all_names);
    
            positions = malloc(all_names * sizeof(char*));
    
            //create pos array
            fd=open(argv[2],O_RDWR|O_CREAT,S_IRWXU);
            for(i=0; i<all_names; i++){
                positions[i] = malloc((MAX_SIZE+1)*sizeof(char));
                for(j=0; ;j++){
                    read(fd,&positions[i][j],1);
                    if (positions[i][j] == ' ') {
                        break;
                    }
                }
            }
            //print pos array
            for(i=0; i<all_names; i++){
                printf("%s\n", positions[i]);
            }
    
            //create data array
            data = malloc(all_names * sizeof(char*));
    
            fd=open(argv[1],O_RDWR|O_CREAT,S_IRWXU);
            for(i=0; i<all_names; i++){
                data[i] = malloc((MAX_SIZE+1)*sizeof(char));
    
                int end = atoi(positions[i]);
                lseek(fd,0,start);
                read(fd,data[i],(end-start));
                data[i][end - start] = 0;
                start = end;
    
            }
    
            qsort(data, all_names, sizeof(char*), strcmp);
    
            for(int i=0; i<all_names; ++i)
            {
                printf("%s\n", data[i]);
            }
    
            /*//print data array
            start = 0;
            for(i=0; i<all_names; i++){
                int end = atoi(positions[i]);
                for(j=0;j<(end-start) ;j++){
                    printf("%c",data[i][j]);
                }
                printf("\n");
            }*/
    
        }
    
    }while(1);
    

    }

    最佳答案

    我猜测 MAX_SIZE 是字符串的最大大小。

    但它应该是sizeof(char*)

    函数qsort需要一个指示每个元素大小的参数。 数据类型 char** 中每个元素的大小是 char* 的大小。

    这是一个与您的程序类似的示例,对于快速测试很有用。

    #include <stdio.h>
    #include <stdlib.h>
    #include <string.h>
    
    int main(int argc, char** argv) {
    
        int all_names = argc;
    
        char** data = argv;
    
        qsort(data, all_names, sizeof(char*), strcmp);
    
        for(int i=0; i<all_names; ++i)
        {
            printf("%s\n", data[i]);
        }
    
        return 0;
    }
    

    关于您更新的代码,在此行之后:

    read(fd,data[i],(end-start));
    

    您应该以空值终止您的字符串。

    data[i][end - start] = 0;
    

    我这样说是假设 end - start 不考虑空终止字符,并且您没有在正在读取的文件中存储空终止字符。

    关于您的附加更新,如果您不想将空终止符写入文件,则只需在将字符串写入文件之前使用 strlen 查找字符串的长度即可。您的另一个选择是为 qsort 编写一个包装器,如下所示。

    int cmp_string_block(const void* a, const void* b) {
        return memcmp(a, b, MAX_SIZE);
    }
    

    然后将该函数传递给 qsort 而不是 strcmp

    关于c - 打印字符串数组行时出现段错误,逐个字符打印时工作正常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59072635/

    相关文章:

    c++ - 从 3 个 vector 中删除重复项

    c - 从 BMP 文件读取到 C 中的 BMP 头结构

    c - 椭圆曲线例程 :o2i_ECPublicKey:passed a null parameter:ec_asn1. c:1271:

    python - 在 Python 中实现函数的前向声明

    c - ctypes.struct(打包)中的 sizeof 与 C 中的打包结构不匹配

    java - 如何找到给定字符串中最长的单词?

    C Windows - 内存映射文件 - 共享结构内的动态数组

    python - 在python中提取不匹配的字符串

    c++ - 尝试添加到 C++ 中的 LinkedList。获取段错误

    linux - 段错误很奇怪