簡體   English   中英

在此程序的情況下,為什么strcpy()函數會產生不需要的輸出?

[英]Why does the strcpy() function produce unwanted outputs in the case of this program?

我試圖在C中創建一個鏈表,而這篇文章是指我試圖在結構中的變量中分配用戶輸入的字符串值的部分。 如果我使用strcpy()而不是strdup(),則程序可以完美地編譯,但是我得到了不需要的輸出。

該程序可以正常編譯,並且不給出警告或錯誤。 如果使用strdup(),那么程序將按預期工作,但是我想知道為什么當使用strcpy()時它不起作用。 在傳遞名稱字符串時,在打印列表時,它有時會打印為null,然后終止,或者打印“ Name:Name:Name:Name:Nam”或其他此類不可預測的錯誤。 任何其他評論或批評都將不勝感激,同時我也正開始學習該語言,謝謝。

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

struct addressBook {
    char *name;
    int age;
    char *phoneNumber;
    struct addressBook *next;
};

static struct addressBook *head = NULL;
static struct addressBook *current;
static struct addressBook *createNew;

//function prototypes
void addNode(void);
struct addressBook * createNode(void);
void printAddressBook(void);
void printStats(void);


int main(void)
{
    addNode();
    addNode();
    printAddressBook();
    addNode();
    addNode();
    printAddressBook();
}

struct addressBook * createNode(void)
{
    struct addressBook *newNode;
    newNode = (struct addressBook *) malloc(sizeof(struct addressBook));

if (newNode == NULL)
{
    puts("Memory error");
    exit(1);
}

printf("\nEnter persons name: ");
char name[20];
scanf("%s", name);
strcpy(newNode -> name, name); //produces unpredictable results
//newNode -> name = strdup(name);   Works fine with strdup

printf("Enter persons age: ");
scanf("%d", &newNode -> age);

printf("Enter persons phone number: ");
char phoneNumber[15];
scanf("%s", phoneNumber);
strcpy(newNode -> phoneNumber, phoneNumber); //produces unpredictable 
results
//newNode -> phoneNumber = strdup(phoneNumber);  Works fine with strdup

return(newNode);
}

void addNode(void)
{
    createNew = createNode();
    current = createNew;
    current -> next = head;
    head = current;
}

void printAddressBook(void)
{
    struct addressBook *temp;
    temp = head;
    while(temp)
    {
        printf("Name: %s\nAge: %d\nPhoneNumber: %s\n\n\n",
               temp -> name,
               temp -> age,
               temp -> phoneNumber);
        temp = temp -> next;
    }
}

當您定義類似char *name;的指針時char *name; 它指向某個隨機位置,因為您尚未初始化它。 寫入指針是非法的,這樣做會調用未定義行為。

strcpy基本上將字符串寫入此調用UB的隨機指針位置。
另一方面, strdup為該字符串動態分配所需的內存,將字符串復制到該位置,然后返回該位置的開始。 您可以讀/寫該存儲位置,因此這是有效的。

暫無
暫無

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

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