如何解决C中动态内存分配的问题?
How to solve problem with dynamic memory allocation in C?
这是任务;
定义一个接受两个整数参数的函数。函数 returns 指向它将动态分配的整数值的指针。如果参数值相同,则实现一个函数为整型变量动态分配内存。分配时的函数应将变量初始化为 0。如果参数不具有相同的值,则不会分配内存并且函数 returns NULL.
我创建了我的代码,但我认为它不好:
#include <stdio.h>
#include <stdlib.h>
int* funk(int a, int b ){
int *p;
if(a == b){
p = (int*)calloc(a,sizeof(int));
return p;
}
else{
return NULL;
}
}
int main(void){
int *p = NULL;
p = funk(4 , 4);
printf("%d", *p);
free(p);
return 0;
}
那么,有人可以检查此代码并帮助我吗?
所以你知道,这是一个非常人为的练习。您通常不必为单个整数分配内存。但是有时 return 一个指针,有时 returns NULL 的函数是一个真正的问题。
在 C 语言中,您经常需要注意函数无法 return 有效值。在这种情况下,您需要在尝试打印和释放它之前检查 funk
没有 return NULL。尝试使用 NULL 指针是 undefined behavior and you risk a memory violation such as a segmentation fault.
int *p = funk(4 , 4);
if( p != NULL ) {
printf("p = %d\n", *p);
free(p);
}
else {
puts("Give us the funk");
}
此外,您只想分配一个整数,因此将 1 作为单元数传递给 calloc
。 don't cast calloc nor malloc,这是不必要的混乱。 C 会为你演员。
// Allocate space for 1 integer, initialize it to 0, and assign it to p.
p = calloc(1, sizeof(int));
这是任务;
定义一个接受两个整数参数的函数。函数 returns 指向它将动态分配的整数值的指针。如果参数值相同,则实现一个函数为整型变量动态分配内存。分配时的函数应将变量初始化为 0。如果参数不具有相同的值,则不会分配内存并且函数 returns NULL.
我创建了我的代码,但我认为它不好:
#include <stdio.h>
#include <stdlib.h>
int* funk(int a, int b ){
int *p;
if(a == b){
p = (int*)calloc(a,sizeof(int));
return p;
}
else{
return NULL;
}
}
int main(void){
int *p = NULL;
p = funk(4 , 4);
printf("%d", *p);
free(p);
return 0;
}
那么,有人可以检查此代码并帮助我吗?
所以你知道,这是一个非常人为的练习。您通常不必为单个整数分配内存。但是有时 return 一个指针,有时 returns NULL 的函数是一个真正的问题。
在 C 语言中,您经常需要注意函数无法 return 有效值。在这种情况下,您需要在尝试打印和释放它之前检查 funk
没有 return NULL。尝试使用 NULL 指针是 undefined behavior and you risk a memory violation such as a segmentation fault.
int *p = funk(4 , 4);
if( p != NULL ) {
printf("p = %d\n", *p);
free(p);
}
else {
puts("Give us the funk");
}
此外,您只想分配一个整数,因此将 1 作为单元数传递给 calloc
。 don't cast calloc nor malloc,这是不必要的混乱。 C 会为你演员。
// Allocate space for 1 integer, initialize it to 0, and assign it to p.
p = calloc(1, sizeof(int));