为什么当我将二维数组放入值时,二维数组在索引处显示正确的值,而不是以后尝试访问的值? (C)

问题描述 投票:0回答:1

我正在编写一个程序,该程序读取linux影子文件,将每一行定界为ID,盐和加密密码的哈希值。我为这些值中的每一个创建了一个二维char数组,并在遍历每一行时用这些值填充了它。当我将这些值输入数组时,我将其打印出来只是为了表明它正在输入正确的值,如下所示:

printf(id: %s, salt: %s", ids[num_accounts], salts[num_accounts]);

其结果如下:

id: root, salt: NrF46O1p
id: seed, salt: wDRrWCQz
id: user1, salt: LGOwUL7Q
id: user2, salt: CL5Fr2bN
id: user3, salt: Un/lqxkl
id: user4, salt: Lx2zrG31
id: user5, salt: 6R1eYOtL

这是在输入每个值时完成的。输入所有值并且程序退出while循环后,还有另一个for循环可打印出所有值(用于调试)

for(int i = 0; i < num_accounts; i++){
     printf("salt %d: %s\n", i, salts[i]);

其结果如下:

salt 0:
salt 1:
salt 2: 6R1eYOtL
salt 3: 6R1eYOtL
salt 4: 6R1eYOtL
salt 5: 6R1eYOtL
salt 6: 6R1eYOtL
salt 7: (null)

这是我分配二维数组并填充它的代码:

char **ids;
char **hashes;
char **salts;

hashes = malloc((num_accounts + 1) * sizeof(char*));
salts = malloc((num_accounts + 1) * sizeof(char*));
ids = malloc((num_accounts + 1) * sizeof(char*));

for(int i = 0; i < num_accounts; i++){
     hashes[i] = malloc(88);
     salts[i] = malloc(8);
     ids[i] = malloc(15);
}

shadow = fopen("shadow", "r");
num_accounts = 0;
while(fgets(shdw_line, SHDW_LINE_LEN, shadow)!=NULL){
     char *token = strtok(shdw_line, ":");
     char *shdw_hash = strtok(NULL, ":");
     if(strcmp(shdw_hash, "*")!=0 && strcmp(shdw_hash, "!")!=0){
        ids[num_accounts] = token;
        token = strtok(shdw_hash, "$");
        token = strtok(NULL, "$");
        salts[num_accounts] = token;
        token = strtok(NULL, "$");
        hashes[num_accounts] = token;
        printf("%d: id: %s, salt: %s\n", num_accounts, ids[num_accounts], salts[num_accounts]);
        num_accounts++;
     }
}

我想知道为什么数组会被输入的最后一个值覆盖?

c arrays pointers dynamic-memory-allocation
1个回答
0
投票

salts [i] = malloc(8);

更改为

salts [i] = malloc(9); // 1为字符串的标志结尾更多其基本背景知识


salts [num_accounts] =令牌; //将为您提供源字符串的指针,因此您将获得全部相同的信息

更改为

strcpy(salts [num_accounts],token);

© www.soinside.com 2019 - 2024. All rights reserved.