简单C代码(指针)出错

w2l*_*ame 0 c pointers

在下面的代码中,使用libxml库:

key = xmlNodeListGetString(doc, cur3->xmlChildrenNode, 1);
                if (flag == 1)
                {
                        image2 = key;
                        printf("the image 2 is %s \n", image2);
                        flag = 2;
                }
                if(flag == 0)
                {
                        image1 = key;
                        printf("the image 1 is %s \n", image1);
                        flag = 1;
                }
                    //printf("SRC of the file is: %s\n", key);

                xmlFree(key);
            printf("the image 1 is %s \n", image1);
Run Code Online (Sandbox Code Playgroud)

两个printf给了我不同的输出.

输出是:

the image 1 is 1.png 
the image 1 is 0p?  g 
the image 2 is 2.png 
the image 1 is 0p?  g
Run Code Online (Sandbox Code Playgroud)

Fab*_*dre 6

行后image1 = key,image1key指向相同的内存区域.

我想xmlFree(key);改变这个记忆区域.如果你希望这个字符串的内容存活到xmlFree,你应该考虑在deallocationg指针之前使用strcpy函数.