我有以下程序导致程序崩溃:
void parseLinear(xmlDocPtr doc, xmlNodePtr node, struct daastXML *xmlFile){
// Set up Linear Property Here
struct daastLinear *Linear;
Linear = (struct daastLinear *) malloc (sizeof(struct daastLinear));
// Assign Property
xmlFile->Ads->data->Inline->Creatives->data->linear = Linear;
// ***** THIS IS FINE HERE
struct daastMediaFile *newMediaFile;
newMediaFile = (struct daastMediaFile *) malloc (sizeof(struct daastMediaFile));
do {
// ***** PROGRAM CRASHES IF I PUT IT HERE INSTEAD
//struct daastMediaFile *newMediaFile;
//newMediaFile = (struct daastMediaFile *) malloc (sizeof(struct daastMediaFile));
if (xmlStrcmp (node->name, XMLSTR("Duration")) == 0){
char *nodeValue = (char *) node->children->content;
xmlFile->Ads->data->Inline->Creatives->data->linear->duration = malloc (sizeof(char));
strcpy (xmlFile->Ads->data->Inline->Creatives->data->linear->duration, nodeValue);
} else if (xmlStrcmp (node->name, XMLSTR("MediaFiles")) == 0){
//
parseMediaFiles(doc,node->children,xmlFile);
}
} while ((node = node->next));
}
问题出在以下几行:
struct daastMediaFile *newMediaFile;
newMediaFile = (struct daastMediaFile *) malloc (sizeof(struct daastMediaFile));
如果我将这些放在循环之外,程序运行正常,但是如果我将它们放在循环中,它就会崩溃而且我看不到任何错误日志。
有谁知道这里发生了什么?
编辑和可能的修复? 这是MediaFile的原始结构:
//THIS CAUSES A CRASH
struct daastMediaFile {
char *id;
char *delivery;
char *type;
char *url;
char *bitRate;
};
但是添加一个int变量,它会起作用吗?
//THIS CAUSES A CRASH
struct daastMediaFile {
char *id;
char *delivery;
char *type;
char *url;
char *bitRate;
int MediaID;
};
答案 0 :(得分:1)
xmlFile->Ads->data->Inline->Creatives->data->linear->duration = malloc (sizeof(char));
这只为一个字符分配内存。在C中,它可能只包含一个空字符串(因为最后一个字符是' \ 0')。这是你的意图吗?
答案 1 :(得分:-1)
//Outside the loop
typedef struct daastMediaFile *daastMediaFiles;
daastMediaFiles newMediaFile;
//In the loop, if needed. free() is important in end of loop
newMediaFile = malloc(sizeof *newMediaFile);
...
free(newMediaFile);