C语言矩阵容量超过16时realloc失败是什么原因?该如何修复?
问题代码的错误点
- 内存分配大小计算错误:
matrix是char**类型,存储的是指针,分配内存时应该用sizeof(char*)作为单位,你代码里写成了sizeof(char),64位系统下char*占8字节,你只给每个元素分配了1字节内存,空间严重不足,之前16容量能运行完全是内存布局巧合,越界后没有触发崩溃而已。 - 字符串赋值逻辑错误:
matrix[words] = tmp_word是直接把栈数组tmp_word的地址赋值给矩阵元素,不是复制字符串内容,最后所有矩阵元素都指向同一个栈地址,内容会被后续输入覆盖,而且后续free栈地址会直接触发段错误。 realloc使用逻辑错误:直接把realloc返回值赋值给原指针,如果realloc失败返回NULL会导致原有内存泄漏;另外realloc后循环遍历所有元素判断是否为NULL完全无意义,前cap个元素已经是之前分配好的有效指针,新扩容的区域才是未初始化的,根本不需要做这个检查。- 输入溢出风险:
fscanf读%s没有限制长度,输入超过128字符时会溢出tmp_word数组,破坏栈内存。
修复后完整代码
#include <stdio.h> #include <stdlib.h> #include <string.h> int main(){ int cap; printf("Give capacity: "); scanf("%d", &cap); // 修正分配单位为char* char** matrix = malloc(sizeof(char*) * cap); if (matrix == NULL) { printf("Memory allocation failed\n"); exit(1); } for (int i = 0; i < cap; ++i) { matrix[i] = malloc(sizeof(char)*129); if (matrix[i] == NULL) { printf("Memory allocation failed\n"); exit(1); } } char tmp_word[129]; int words = 0; // 修正读入长度限制,避免溢出 while (fscanf(stdin,"%128s",tmp_word) != EOF){ // 修正字符串复制逻辑,拷贝内容而非赋值地址 strcpy(matrix[words], tmp_word); words++; printf("words stored: %d, Capacity: %d\n", words, cap); if (words == cap){ printf("Limit reached, reallocating....\n"); // 修正realloc使用逻辑,先存临时指针避免内存泄漏 char** temp = realloc(matrix, sizeof(char*) * 2 * cap); if (temp == NULL) { printf("Memory reallocation failed due to a lack of memory\n"); exit(1); } matrix = temp; printf("1D reallocated\n"); cap *= 2; printf("Capacity increased\n"); for (int i = (cap/2); i < cap; ++i) { matrix[i] = malloc(sizeof(char)*129); if (matrix[i] == NULL) { printf("Memory allocation failed for new element\n"); exit(1); } } printf("Succesful reallocation, new capacity: %d\n", cap); } } for (int i = 0; i < cap; ++i) { free(matrix[i]); } free(matrix); return 0; }
内容的提问来源于stack exchange,提问作者Myxy290
相关产品推荐
相关产品推荐

