[英]Why don't I get a compilation error when I miss the dynamic memory allocation in C?
Let's suppose I am trying to write a function that creates a simple linked list in C.假设我正在尝试编写一个在 C 中创建简单链表的函数。
The function is like this:函数是这样的:
node* createLinkedList(int n) {
int i = 0;
node* head = NULL;
node* temp = NULL;
node* p = NULL;
for (i = 0; i < n; i++) {
//create isolated node
temp = malloc(sizeof(node));
printf_s("\nEnter the data for node number %i:", i);
scanf_s("%d", &(temp->data));
temp->next = NULL;
if (head == NULL) {
//if list is empty then make temp as first node
head = temp;
}
else {
p = head;
while (p->next != NULL)
p = p->next;
p->next = temp;
}
}
return head;
}
If I purposely delete the line temp = malloc(sizeof(node));
如果我故意删除行
temp = malloc(sizeof(node));
the program compile just fine but I get a runtime error (obviously).程序编译得很好,但我得到一个运行时错误(显然)。
My question is: Shouldn't the compiler warn me that I did not allocate memory for the temp
variable?我的问题是:编译器不应该警告我没有为
temp
变量分配内存吗? Is it allocating that memory implicitly?它是隐式分配内存吗? If so, how?
如果是这样,如何?
By definition, malloc
doesn't allocate memory implicitly.根据定义,
malloc
不会隐式分配内存。 It's the purpose of this function to return a valid memory address, which obviously can't be verified by the compiler as it will be called during runtime.这个函数的目的是返回一个有效的内存地址,这显然不能被编译器验证,因为它将在运行时被调用。
At this point, the compiler just assumes that the pointer is a valid one.此时,编译器只是假设指针是有效的。 It can't guess if the pointer is already pointing to a valid memory address or not.
它无法猜测指针是否已经指向有效的内存地址。
Shouldn't the compiler warn me that I did not allocate memory for the temp variable?
编译器不应该警告我我没有为临时变量分配内存吗?
Nope.不。 The allocation is done during runtime.
分配是在运行时完成的。 The best the compiler can do is to warn you if an variable is not initialized.
编译器能做的最好的事情就是在变量未初始化时发出警告。 And this is the reason why I think it's a bad idea to initialize pointers to NULL;
这就是为什么我认为将指针初始化为 NULL 是个坏主意的原因;
$ cat main.c
int main(void)
{
int *p;
*p =42;
}
$ gcc main.c -Wall -Wextra
main.c: In function ‘main’:
main.c:4:8: warning: ‘p’ is used uninitialized in this function [-Wuninitialized]
4 | *p =42;
| ~~~^~~
If you change int *p;
如果你改变
int *p;
to int *p = NULL;
到
int *p = NULL;
you will not get that warning.你不会得到那个警告。
To simplify it a bit.稍微简化一下。 The compiler has absolutely no idea whatsoever about allocation.
编译器对分配一无所知。 The return value from
malloc
is simply an address. malloc
的返回值只是一个地址。 In that regard, these three statements are not fundamentally different:在这方面,这三个声明没有根本区别:
int *p = NULL;
int *p = &k;
int *p = malloc(sizeof *p);
In all three cases, p is assigned the value of an address.在所有三种情况下,p 都被分配了一个地址的值。 The compiler has no way to know if that address points to a valid memory address or not.
编译器无法知道该地址是否指向有效的内存地址。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.