【发布时间】:2012-03-15 15:54:15
【问题描述】:
对于有 C 经验的人来说,这将是一个简单的内存分配/引用问题:
这是我的数据结构:
struct configsection {
char *name;
unsigned int numopts;
configoption *options;
};
typedef struct configsection configsection;
struct configfile {
unsigned int numsections;
configsection *sections;
};
typedef struct configfile configfile;
这是我初始化配置部分或配置文件以及将配置部分添加到配置文件的例程:
// Initialize a configfile structure (0 sections)
void init_file(configfile *cf) {
cf = malloc(sizeof(configfile));
cf->numsections = 0;
}
// Initialize a configsection structure with a name (and 0 options)
void init_sec(configsection *sec, char *name) {
sec = malloc(sizeof(configsection));
sec->numopts = 0;
sec->name = name;
printf("%s\n", sec->name);
}
// Add a section to a configfile
void add_sec(configfile *cf, configsection *sec) {
// Increase the size indicator by 1
cf->numsections = cf->numsections + 1;
// Reallocate the array to accommodate one more item
cf->sections = realloc(cf->sections, sizeof(configsection)*cf->numsections);
// Insert the new item
cf->sections[cf->numsections] = *sec;
}
我相信我的问题源于我的 init_sec() 函数。这是一个例子:
int main(void) {
// Initialize test configfile
configfile *cf;
init_file(cf);
// Initialize test configsections
configsection *testcs1;
init_sec(testcs1, "Test Section 1");
// Try printing the value that should have just been stored
printf("test name = %s\n", testcs1->name);
虽然init_sec() 中的printf() 成功打印了我刚刚存储在配置部分中的名称,但在main() 的printf() 中尝试相同的操作会产生分段错误。此外,addsec() 会产生分段错误。
【问题讨论】:
-
@IntermediateHacker:谢谢。这是有原因的吗?
-
好吧,如果您只是使用标准 C,则不会。但有时,使用 GObject 等可能会导致问题
标签: c pointers memory-management reference