我会问你一些真正简单的实现搜索计划算法的程序的帮助。那么,我得到的问题对我来说有点奇怪:在为函数中的本地声明的简单字符数组分配内存之后,我在这个数组上工作,它具有所有期望的行为并且一切正常,但是当我调用在函数结束之前,向该数组释放()函数,程序停止并中止。如果有人遇到这个问题(或者不是)可以帮助我,我会非常感激。那么,这里遵循的“模拟”几行代码来展示一下我说的(它不正是上写的,但:释放先前分配的内存后程序中止
char* v_AllTheWorld
char* v_ReadALineOfTheWorld;
v_AllTheWorld = malloc(COLUMNS * LINES * sizeof(char)); /*LINES and COLUMNS are defined constants*/
if(v_AllTheWorld == NULL)
{
fprintf(stderr, "..."); //etc, etc.
exit(1);
}
v_ReadALineOfTheWorld = malloc(COLUMNS * sizeof(char)); /*the "sizeof(char)" looks useless, but there's no point in talking about that here, i guess.*/
if(v_ReadALineOfTheWorld == NULL)
{
fprintf(stderr, "..."); //etc, etc.
exit(1);
}
while(/*some_condition (number of lines to be read)*/)
{
//read data string from stream and stores in v_ReadALineOfTheWorld (fscanf);
//appends the read data to v_AllTheWorld (strncat);
}
free(v_ReadALineOfTheWorld);
/*The program is stopping right after this call in the debug.*/
return v_AllTheWorld;
我没有把函数的头部,报关,并且我没有表示数据流或数据如何被详细处理,但是没有其他的“malloc”或“free”调用被创建,并且所有写入的代码都被无条件地执行(超出了“if “或类似的)当然,最后一个行为不包括配置测试,但你得到了我说的。
所以,我希望我这样做是正确的要求这种方式,我希望我详细问题是正确的,希望你能帮助我。
哦,我差点忘了:你可能已经注意到,该方案是C.
我们可以看到while循环的内容吗?我怀疑你正在增加'v_ReadALineOfTheWorld'指针,其中'free(v_ReadALineOfTheWorld)'会导致未定义的行为。请注意,您释放的指针应与从malloc返回的指针相同。 – Naveen 2012-04-17 05:01:27
您是否尝试使用GDB并查看内存位置? – noMAD 2012-04-17 05:01:53
另外,尝试'calloc(v_ReadALineOfTheWorld,0)' – noMAD 2012-04-17 05:04:56