簡體   English   中英

C沒有為新的char數組分配內存

[英]C not allocating memory for new char array

我看不到以下代碼如何在字符數組cd2被覆蓋的情況下工作。 我試圖為兩個字符串分配空間,然后用crypt函數的結果填充它們。 我不確定crypt在這里扮演了多大的角色,或者這是否會帶來其他一些字符串操作功能。 但是以下輸出不應相同, 它們應具有不同的值。 但是它們都是“ ttxtRM6GAOLtI”,我試圖從“ ss”開始輸出

#include <crypt.h>
#include <unistd.h>
#include <pwd.h>
#include <string.h>
#include <stdio.h>

int main(int argc, string argv[])
{
    char *cd;  
    cd = malloc(30 * sizeof(*cd));
    char *cd2; 
    cd2 = malloc(30 * sizeof(*cd2));

    cd2 = crypt("yum", "ss");
    cd = crypt("yum", "tt");

    printf("hasehd 'yum' with 'tt' salt is %s\n",cd);
    printf("hasehd 'yum' with 'ss' salt is %s\n",cd2);

}

輸出-

   hasehd 'yum' with 'tt' salt is ttxtRM6GAOLtI
   hasehd 'yum' with 'ss' salt is ttxtRM6GAOLtI

更新:我將其更改為不使用malloc,但我認為我必須通過char數組的聲明來分配內存。 由於crypt覆蓋靜態緩沖區,因此我需要在覆蓋之前將結果提供給其他地方。

#include <crypt.h>
#include <unistd.h>
#include <pwd.h>
#include <string.h>
#include <stdio.h>

int main(int argc, string argv[])
{
 char ch1[30];
 char ch2[30];
 char *cd;
 char *cd2;
 cd = &ch1[0];  
 cd2 = &ch2[0]; 

 snprintf(cd2, 12, "%s\n", crypt("yum", "ss"));
 snprintf(cd, 12, "%s\n", crypt("yum", "tt"));

 printf("hasehd 'yum' with 'tt' salt is %s\n",cd);
 printf("hasehd 'yum' with 'ss' salt is %s\n",cd2);

}

輸出-

hasehd 'yum' with 'tt' salt is ttxtRM6GAOL
hasehd 'yum' with 'ss' salt is ssqDHVWOCwe

更新:我按照建議使用了strcpy ,並且使用了malloc為數組分配空間。 strcpy似乎更干凈一些,因為我不需要提供長度。

#include <crypt.h>
#include <unistd.h>
#include <pwd.h>
#include <string.h>
#include <stdio.h>

int main(int argc, string argv[])
{
  int PWORD_LENGTH = 30;

   char *cd;
   char *cd2;
   cd = malloc(sizeof(char) * (PWORD_LENGTH + 1));
   cd2 = malloc(sizeof(char) * (PWORD_LENGTH + 1));

   strcpy(cd2, crypt("yum", "ss"));
   strcpy(cd, crypt("yum", "tt"));

   printf("hasehd 'yum' with 'tt' salt is %s\n",cd);
   printf("hasehd 'yum' with 'ss' salt is %s\n",cd2);

}

輸出-

hasehd 'yum' with 'tt' salt is ttxtRM6GAOL
hasehd 'yum' with 'ss' salt is ssqDHVWOCwe

crypt()返回一個指向靜態分配緩沖區的指針。 每次對crypt()調用都會覆蓋先前的結果。

http://man7.org/linux/man-pages/man3/crypt.3.html

返回值指向靜態數據,其每次調用都會覆蓋其內容。

在這種情況下,不需要malloc調用。 實際上,您最終會遇到無法訪問的內存,您現在無法free內存,因為您用crypt()的結果覆蓋了指針

crypt()函數具有內部存儲器,每個調用都會覆蓋以前的結果。

為'ss'然后為'tt'調用crypt()printf()

或使用可重入版本

#define _GNU_SOURCE 1
#include <crypt.h>
#include <unistd.h>
#include <pwd.h>
#include <string.h>
#include <stdio.h>
#include <stdlib.h>

int main(int argc, char *argv[])
{
    char *cd;
    cd = malloc(30 * sizeof(*cd));
    char *cd2;
    cd2 = malloc(30 * sizeof(*cd2));

    struct crypt_data *data = calloc(1, sizeof (struct crypt_data));
    struct crypt_data *data2 = calloc(1, sizeof (struct crypt_data));

    cd2 = crypt_r("yum", "ss", data2);
    cd = crypt_r("yum", "tt", data);

    printf("hasehd 'yum' with 'ss' salt is %s\n",cd2);
    printf("hasehd 'yum' with 'tt' salt is %s\n",cd);

}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM