[英]Why don't I get a compilation error when I miss the dynamic memory allocation in C?
假设我正在尝试编写一个在 C 中创建简单链表的函数。
函数是这样的:
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;
}
如果我故意删除行temp = malloc(sizeof(node));
程序编译得很好,但我得到一个运行时错误(显然)。
我的问题是:编译器不应该警告我没有为temp
变量分配内存吗? 它是隐式分配内存吗? 如果是这样,如何?
根据定义, malloc
不会隐式分配内存。 这个函数的目的是返回一个有效的内存地址,这显然不能被编译器验证,因为它将在运行时被调用。
此时,编译器只是假设指针是有效的。 它无法猜测指针是否已经指向有效的内存地址。
编译器不应该警告我我没有为临时变量分配内存吗?
不。 分配是在运行时完成的。 编译器能做的最好的事情就是在变量未初始化时发出警告。 这就是为什么我认为将指针初始化为 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;
| ~~~^~~
如果你改变int *p;
到int *p = NULL;
你不会得到那个警告。
稍微简化一下。 编译器对分配一无所知。 malloc
的返回值只是一个地址。 在这方面,这三个声明没有根本区别:
int *p = NULL;
int *p = &k;
int *p = malloc(sizeof *p);
在所有三种情况下,p 都被分配了一个地址的值。 编译器无法知道该地址是否指向有效的内存地址。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.