【发布时间】:2016-01-02 16:29:38
【问题描述】:
我正在学习 C(C++) 中内存分配的基础知识。
#include "stdio.h"
#include "string.h"
#include "stdlib.h"
void main(){
char *str;
char *input;
int *ilist;
int i, size1, size2;
printf("Number of letters in word: ");
scanf("%d", &size1);
printf("Number of integers: ");
scanf("%d", &size2);
str = (char *)malloc(size1*sizeof(char) + 1);
ilist = (int *)malloc(size2*sizeof(int));
if (str == NULL || ilist == NULL){
printf("Lack of memory");
}
printf("Word: ");
int k = size1;
// the following line is done to prevent memory bugs when the amount of
letters in greater than size1.
scanf("%ks", &str); //I guess something is wrong with this line
/* user inputs a string */
for (i = 0; i < size2; i++) {
printf("Number %d of %d: ", i + 1, size2);
//this scanf is skipped during the execution of the program
scanf("%d", ilist + i);
}
free(str);
free(ilist);
system("pause");
}
程序要求用户写出单词中字母的数量和数字中的位数。然后用户写这个词。然后他根据之前输入的数字一个接一个地写入整数。我遇到的问题是当用户写下整个单词时,会跳过下一个 scanf。 谢谢你。 附:此代码中是否还有其他类型的内存错误?
【问题讨论】:
-
检查
scanf的返回值是个好主意。 -
第一课 c != c++ 并且在 c 中您不需要将
malloc()转换为目标指针类型,因为您不需要。 -
我建议安装 Valgrind valgrind.org 来检查内存泄漏。
-
@EdHeal;否。从 C99 开始,返回类型应为
int。 -
@EdHeal:对于托管环境/它是 UB,根据 C11 标准附录 J2 以及 5.1.2.2.1。
标签: c dynamic-memory-allocation