我有一些指针麻烦.
这是他们的声明(主要):
int *dot_positions = (int *)malloc(sizeof(int));
char *str = (char *)malloc((MAX_N + 1) * sizeof(char));
Run Code Online (Sandbox Code Playgroud)
其中MAX_N为100,并且是字符串的限制.dot_positions [0] = -1;
我在'dot_position'的第一个位置添加一个值,然后,在运行时,我调用以下函数来添加其他值.
int add_dot_to_array(int *array, int position, int array_len) {
array = (int *)realloc(array, array_len + 1);
array[array_len] = position;
return array_len + 1;
}
Run Code Online (Sandbox Code Playgroud)
在main()的末尾,我释放了指针:
free(str);
free(dot_positions);
Run Code Online (Sandbox Code Playgroud)
但这会导致我的程序崩溃.我在Windows x64机器上使用Orwell Dev-C++和Mingw.我也确定那些指针不是NULL.怎么了?提前致谢!
您正在丢失地址realloc()返回,因为您没有在调用者的环境中重新设置指针.这会导致指针(来自原始malloc())变得陈旧,并使其崩溃.
要解决此问题,请将其设置为add_dot_to_array(int **array, int position, int array_len)可以更改调用者的指针.另外,还要确保你没有realloc()在每个另外,因为这将杀死性能.
另外,不要malloc()在C中强制转换返回值,也不要"缩放"字符串分配sizeof (char).