[英]C - freeing up memory after 2D array
I'm having a problem.我有问题。 I created a 2D array, and in the end, i would like to free it.
我创建了一个二维数组,最后,我想释放它。 Where's the problem in my code?
我的代码哪里出了问题? If i run my program everything works fine, until the end.
如果我运行我的程序一切正常,直到结束。 It never prints out Succes!, so I think it bugs out before that point.
它永远不会打印出成功!,所以我认为在那之前它会出错。 Any help?
有什么帮助吗?
Here's my code :
这是我的代码:
#include<stdio.h>
#include<stdlib.h>
int main()
{
int n=5;
int size=51;
char **a_name=(char**)malloc(sizeof(char*)*n);
for(int i=0;i<n;i++){
a_name[i]=(char*)malloc(sizeof(char)*size);
scanf("%s",a_name[i]);
}
for(int i=0;i<n;i++){
printf("%s\n",a_name[i]);
}
n=6;
*a_name=realloc(*a_name,sizeof(char*)*n);
scanf("%s",a_name[n-1]);
printf("\n");
for(int i=0;i<n;i++){
printf("%s\n",a_name[i]);
}
for(int i=0;i<n;i++){
free(a_name[i]);
}
free(a_name);
printf("Succes!\n");
return 0;
}
Firstly, change首先,改变
*a_name = realloc(*a_name, sizeof(char*) * n);
to到
a_name = (char**)realloc(a_name, sizeof(char*) * n);
You don't want to reallocate the contents of the array of strings ( a_name
) to one of the strings itself ( *a_name
).您不想将字符串数组 (
a_name
) 的内容重新分配给字符串本身 ( *a_name
) 之一。
Secondly, the source of the problem is that after you called the realloc, you didn't call malloc on the newly added elements of a_name
like you did here:其次,问题的根源在于你调用了realloc之后,并没有像这里那样对
a_name
新增元素调用malloc:
for(int i=0;i<n;i++) {
a_name[i] = (char*)malloc(sizeof(char) * size); // here you allocated a 51 byte block for each char*
scanf("%s", a_name[i]);
}
The sixth element of the array is a dynamically allocated pointer, but the array of chars it points to hasn't been allocated the 51 bytes you allocated for the first 5 strings.数组的第六个元素是一个动态分配的指针,但它指向的字符数组尚未分配您为前 5 个字符串分配的 51 个字节。
The solution is to add this line before the second scanf call解决方法是在第二次 scanf 调用之前添加这一行
a_name[n - 1] = (char*)malloc(sizeof(char) * size);
Your final code should look like this您的最终代码应如下所示
#include<stdio.h>
#include<stdlib.h>
int main()
{
int n = 5;
int size = 51;
char **a_name = (char**)malloc(sizeof(char*)*n);
for (int i = 0; i < n; i++) {
a_name[i] = (char*)malloc(sizeof(char)*size);
scanf("%s", a_name[i]);
}
for (int i = 0; i < n; i++) {
printf("%s\n", a_name[i]);
}
n = 6;
a_name = (char**)realloc(a_name, sizeof(char*) * n);
a_name[n - 1] = (char*)malloc(sizeof(char) * size); // allocate memory for the string first
scanf("%s", a_name[n - 1]);
printf("\n");
for (int i = 0; i < n; i++) {
printf("%s\n", a_name[i]);
}
for (int i = 0; i < n; i++) {
free(a_name[i]);
}
free(a_name);
printf("Success!\n");
return 0;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.