无法从c中的堆栈结构复制字符串

标签 c stack structure

我有一个使用结构的堆栈。我需要在弹出时返回一个字符串。所以我尝试使用 strcpy() 将字符串复制到指针,但是当我运行程序时,程序在该步骤停止工作。

这是堆栈的代码。

struct node{            // stack structure
    char data[5];
    struct node *link;
}*top=NULL;

这是 pop 函数的代码。

char* pop(){
    printf("\nIn pop fun.");
    if(top==NULL)
    {
        printf("Error!!!\nStack Underflow.");
        return "error";
    }
    printf("\nChecked if pop is null.");
    char *popvar;
    printf("\nCreated new char pointer.");
    strcpy(popvar,top->data);
    printf("\nCopied data from top.");
    struct node *tmp = top;
    printf("\nCreated new node.");
    top=tmp->link;
    printf("\n Assigned top new value.");
    free(tmp);
    printf("\nFree temp");
    printf("\npoped from stack.");
    return popvar;
}

请大家帮忙...

最佳答案

您不能通过strcpy()或其他方式写入未初始化的指针。这是写入未定义的内存地址,因此行为未定义。

如果您将 strcpy() 声明为一个数组,那么这是合法的:

char popvar[5];
strcpy(popvar, top->data);

或者一个结构节点,它有一个数组(而不是指针)成员:

struct node popvar;
strcpy(popvar.data, top->data);

不过,如果不再次复制这些值,则无法将这些值返回给 pop() 的调用者。为此,您可以分配动态(堆)内存:

char *popvar = malloc(5);
strcpy(popvar, top->data);
top = top->link;
return popvar;

在这种情况下,调用者必须始终记住对此结果调用free()。每个 malloc() 最后必须跟一个 free(),否则就会出现内存泄漏。请注意,您的原始程序调用 free() 从未调用 malloc();这是非法的,其行为未定义。

另一种可能性是要求调用者决定如何存储结果:

void pop(char *result) {
    strcpy(result, top->data);
    top = top->link;
}

此函数允许以下任一用途:

char str[5];
pop(str);

或者:

char *str = malloc(5);
pop(str);
/* do stuff */
free(str);

或者甚至:

struct {
    int foo;
    int bar;
    char other_data[5];
} some_other_structure;
pop(some_other_structure.other_data);

关于无法从c中的堆栈结构复制字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52441064/

相关文章:

C 相邻堆栈寻址

c++ - 为什么C++标准队列有back函数,stack没有bottom函数?

c - 无法在结构中赋值

javascript - 从平面对象结构创建嵌套对象结构

c - 在c中序列化字符串

c - 如何通过 OCI 设置 V$SESSION.PROGRAM?

C - 求和并找到最大/最小

c - 如何制作一个简单的谓词引擎

python - 在 python 脚本中设置堆栈大小

c - 在分配内存之前对灵活成员数组的第一个元素使用 sizeof 是未定义的行为?