简体   繁体   中英

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

I am trying to create a linked list in C and this post refers to the part where I try to assign a variable in a structure a string value that the user inputs. The program compiles perfectly yet if I use strcpy() instead of strdup() then I get unwanted output.

The program compiles fine and gives no warnings or errors. If strdup() is used then the program works as intended but I'd like to know why it doesn't work when strcpy() is used instead. When passing in strings for the names, when the list is printed it will occasionally print null and then terminate or it will instead print "Name:Name:Name:Name:Nam" or other such unpredictable errors. Any other comments or criticisms would be appreciated as well as I am just starting to learn the language, thanks.

#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;
    }
}

When you define a pointer like char *name; it points to some random location as you haven't initialized it. It is illegal to write to the pointer and doing so will invoke Undefined Behavior.

strcpy basically writes the string to this random pointer location invoking UB.
strdup on the other hand, allocates the required memory dynamically for the string, copies the string to that location and then returns the start of the location. You can read/write to this memory location and hence, this is valid.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM