c - 为什么 realloc 会破坏价值?
问题描述
#include<stdio.h>
#include<stdlib.h>
void main()
{
int* list_of_numbers;
list_of_numbers = (int*)malloc(1);
list_of_numbers[0] = 10;
printf("Value at 0 before realloc: %d", list_of_numbers[0]);
list_of_numbers = (int*)realloc(list_of_numbers, 2 * sizeof(int));
printf("Value at 0 after realloc: %d", list_of_numbers[0]);//this one prints -83920310 instead of 10
system("pause");
}
我的任务是要求我为一个数字分配内存并且效果很好然后我需要重新分配它以适应 2 个数字,一旦我这样做,我的第一个值就会被随机值替换。为什么?以及如何修复:D
解决方案
malloc(1)
太小而无法容纳int
,因此在此处写入未定义行为。只是巧合,它一开始似乎有效。做malloc(sizeof(int))
或malloc(sizeof(*list_of_numbers))
代替。
推荐阅读
- r - R dbReadTable 没有返回这样的表错误
- postgresql - 枚举类型的 knex 迁移创建类型已存在
- laravel - youtube-dl norkunas / youtube-dl-php 的 Laravel 和 php 包装器
- c# - Visual Studio c# 项目到 Monodevelop ResolveKeySource 错误
- java - 如何通过 GMail API 使用 GSUITE 组 ID 发送电子邮件?
- google-cloud-dataflow - 使用 Beam 和 DataFlow 将数据从 Cloud SQL 移动到 Elastic Search
- javascript - 如何定位 Jquery Injected Nav
- android - 通过后退按钮设备在 webview 中回退
- ios - 如何获取 KVO #keyPath(WKWebView.url) 的 URL 值?
- javascript - 如何在嵌套代码中使用 Javascript 定位特定元素?