将顶点添加到图中的c实现失败

将顶点添加到图中的c实现失败,c,debugging,C,Debugging,下面是我在图形中添加顶点的玩具程序: #include <stdio.h> #include <ctype.h> #include <stdlib.h> #include <string.h> #include <limits.h> typedef struct EdgeNode{ int adjvex; struct EdgeNode *nextarc; }ENode, *PENode; typedef str

下面是我在图形中添加顶点的玩具程序:

#include <stdio.h>
#include <ctype.h>
#include <stdlib.h>
#include <string.h>
#include <limits.h>
typedef  struct EdgeNode{
     int adjvex;
     struct EdgeNode *nextarc;
 }ENode, *PENode;
typedef struct VertexNode{
     char *data; 
     ENode *firstarc; 
 }VNode;

typedef  struct MyGraph{
     VNode vertices[INT_MAX];

}Graph;



/**void make_node(Graph *G, char *first){
     int i = 0;
     G.vertices[i++].data = first;
     G.vertices[i].firstarc = NULL;
     while(i--){
        printf("the node is %s\n",G.vertices[i].data);
     }                                     
}**/

int main (){                                                                                        
    size_t sz1;
    char *line = NULL;
    //char line[1024];
    char make_nodes[] = "@n";
    char make_edges[] = "@e";
    char check_edges[] = "@q";
    static int  i = 0;
    int  is_make_node = 0;
    //Graph* pGraph;
    Graph* pGraph = malloc(sizeof(Graph));
    if (pGraph == NULL){
        fprintf(stderr, "Unable to allocate memory for new node\n");
        exit(1);
    }


    while(getline(&line, &sz1, stdin) > 0){
        char cmd[3],n1[65],n2[65],dummy[2];
        int num_args;
        num_args = sscanf(line,"%3s%64s%64s%2s",cmd,n1,n2,dummy);
        if (strcmp(cmd,make_nodes) == 0){
            if(num_args != 2){
                printf("error\n");
            }else{
                pGraph->vertices[i].data = n1;
                pGraph->vertices[i].firstarc = NULL;
                printf("the node is %s\n",pGraph->vertices[0].data);
                i++;
            }
        }
    }
        printf("---");
        printf("the node is %s\n",pGraph->vertices[0].data);
        printf("the node is %s\n",pGraph->vertices[1].data);
        printf("the node is %s\n",pGraph->vertices[2].data);
     return 0;
}
@n something意味着添加一个名为something的节点,而I预期的输出应该是:

@n hey
the node is hey
@n jude
the node is jude
---
the node is hey
the node is jude
the node is (null)
有人看到问题了吗?我不知道为什么当我读取一个新顶点时,上一个顶点被新顶点覆盖。

使用pGraph->texts[I]。data=n1;让.data指向具有块作用域的局部变量,一旦超出作用域,该局部变量的生存期将结束。因此,当您访问顶点[x]时,会出现未定义的行为。之后的数据,即在循环之后,甚至在循环中的第二次运行时,会使第一次运行的局部变量无效

要解决此问题,请分配内容的副本:

pGraph->vertices[i].data = malloc(strlen(n1)+1);
strcpy(pGraph->vertices[i].data, n1);
或者简而言之,如果您的平台上提供:

pGraph->vertices[i].data = strdup(n1);

n1的范围是while循环的局部范围。您所做的是未定义的行为,因为.data指向一个超出范围的局部变量幸运的是,堆栈在循环后不会混乱,因此printf成功地访问了这个超出范围的内存区域。请将VNode.data设置为字符数组,或者在复制之前使用malloc动态分配它。您需要对pGraph->vertices[i]使用strcpy或类似工具。data=n1;。pGraph->顶点[i]。数据=n1;=>PGRAPHE->顶点[i]。数据=strdup n1;请注意,使用%s打印空指针将具有未定义的行为。
pGraph->vertices[i].data = strdup(n1);