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

cant copy a string from a stack structure in c

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

这是堆栈的代码。

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

弹出函数的代码如下。

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

任何人请帮助...

动态分配的内存属于程序,即使在范围结束时也存在。

作用域结束后,只有动态分配的内存才能存在,一旦你的函数结束,指针popvar也会结束,但如果:

 #include<stdio.h>
 #include<stdio.h>

 char *fun()
 {
    char *c=malloc(10);
    c[0]='h';
    c[1]='e';
    c[2]='l';
    c[3]='l';
    c[4]='[=10=]';

    return c;
}

int main(){

    printf("%s",fun());

    return 0;   
}

将弹出的数据复制到动态分配的内存中,然后可以从该 pop 函数外部访问该内存。另外,在使用 strcpy 复制它之前,您没有分配要复制弹出值的内存。

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

如果您将数组声明为 strcpy() 是合法的:

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

或者一个struct node,它有一个数组(不是指针)成员:

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

你不能 return 这些值给 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);