簡體   English   中英

字符串和int的串聯導致C中的分段錯誤

[英]Concatenation of string and int results in segmentation fault in C

我不確定自己在做什么錯。 我正在嘗試使用pid連接hostname以創建id

char *generate_id(void) {
    int ret;
    char id[1048];
    char hostname[1024];
    pid_t pid = getpid();
    //hostname[1023] = '\0';

    if ((ret = gethostname(hostname,1024) < 0)) {
        perror("gethostname");
        exit(EXIT_FAILURE);
    }
    sprintf(id, "%s%d", pid);
    printf("hostname is %s\n", hostname);
    printf("The process id is %d\n", pid);
    printf("The unique id is %s", id);

    return id;
}

編輯:

閱讀一些答案后更新了代碼:

char *generate_id(void) {
    int ret;
    char hostname[1024];
    pid_t pid = getpid();
    //hostname[1023] = '\0';

    if ((ret = gethostname(hostname,1024) < 0)) {
        perror("gethostname");
        exit(EXIT_FAILURE);
    }

    int size = snprintf(NULL, 0, "%s%d", hostname, pid);
    char * id = malloc(size + 1);

    printf("hostname is %s\n", hostname);
    printf("The process id is %d\n", pid);
    printf("The unique id is %s\n", id);

    return id;
}

編輯:

工作代碼:

char *generate_id(void) {
    int ret;
    char hostname[1024];
    pid_t pid = getpid();
    //hostname[1023] = '\0';

    if ((ret = gethostname(hostname,1024) < 0)) {
        perror("gethostname");
        exit(EXIT_FAILURE);
    }

    int size = snprintf(NULL, 0, "%s%d", hostname, pid);
    char * id = malloc(size + 1);
    sprintf(id, "%s%d", hostname, pid);
    printf("hostname is %s\n", hostname);
    printf("The process id is %d\n", pid);
    printf("The unique id is %s\n", id);

    return id;
}

您的格式字符串出現問題:

sprintf(id, "%s%d", pid);

您的格式字符串有兩個格式化程序( %s表示字符串, %d表示int ),但是您僅傳遞了pid_t 您可能的意思是:

sprintf(id, "%s%d", hostname, pid);

要么

sprintf(id, "%d", pid);

在您的代碼中, %spid解釋為指針。 嘗試取消引用以格式化字符串會導致分段錯誤,因為它是無效的指針值。

您的內存管理問題:

但是,在代碼中也存在未定義的行為 :您將id聲明為堆棧分配的數組,但是您將返回該數組(此處將衰減為指針)。 這也是錯誤的,以后可能會導致崩潰。

您需要像這樣將id更改為堆分配的數組:

char * id = malloc(1024);

然后, generate_id函數的調用者需要在完成后free內存。

僅分配所需的空間可能是一個好主意。 您可以像這樣使用snprintf

// Determine how much space the string needs.
int size = snprintf(NULL, 0, "%d", pid);
// Allocate the required space plus NULL termination.
char * id = malloc(size + 1);
// Actually print the string.
sprintf(id, "%d", pid);

不確定您要在哪里進行段隔離,但是您有一些問題。

snprintf()更加安全,不會超出id []緩沖區。 sprintf可能會溢出緩沖區

如上所述,sprintf(id,“%s%d”,pid)不好。

return id是錯誤的,因為它將指針返回到堆棧上的值。 一旦您返回,堆棧就不再是您的了。

sprintf(id, "%s%d", pid);

您有兩個選擇器%s和%d,但只有一個參數(pid)。 您需要輸入一個字符串和一個整數,而不只是整數。

暫無
暫無

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

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