Hal*_*Hal 2 c malloc free memory-management
好吧,我已经付出了很多努力,在这里看了很多问题,但我不能完全理解这一点.希望你能在这里解决我的问题!
int main(int argc, char *argv[]){
char read[50];
char *string[10];
while(1){
fgets(read,sizeof read, stdin);
int t = 0; //ticks whenever a non-whitespace char is read
int pos = 0; //keeps track of position in string array
int i;
int j;
for(i = 0; i < sizeof read; i++){
if(isspace(read[i]) && t != 0){
string[pos] = malloc((t+1) * (sizeof(char)));
// int z;
// for(z = 0; z < sizeof string[pos]; z++){
// string[pos][z] = '\0';
// }
for(j = 0; j < t; j++){
string[pos][j] = read[i-(t-j)];
}
t = 0;
pos++;
}
else if(!isspace(input[i])) t++;
}
int k;
for(k = 0; k < pos; k++){
printf("%i: %s\n",k,string[k]);
free(string[k]);
}
}
}
Run Code Online (Sandbox Code Playgroud)
我试图写一个程序将在从用户,然后将其分解成它的构成词的句子阅读中,每个存储在其自己的字符数组.
我使用malloc()来分配足够的内存来适应每个单词,在使用后释放它.
第一次运行很好,但是在后续循环中,短于5个字符的单词(并且只有输入多个单词,用空格分隔)才会正确显示,并附加随机的额外字符/符号.
这可能是因为malloc使用了空闲的释放内存吗?如果是这种情况,我应该如何正确使用malloc?
我发现补救的唯一方法就是使用我已经注释掉的代码.它使用\ 0填充新分配的char数组.
谢谢!
样本输出:
input words(0): we we we
0: we
1: we
2: we
input words(1): we we we
0: we?
1: we?
2: we
Run Code Online (Sandbox Code Playgroud)
你有两个问题:
1)你sizeof read在这里使用条件:
for(i = 0; i < sizeof read; i++){
Run Code Online (Sandbox Code Playgroud)
如果输入线不够长sizeof read怎么办?你应该strlen(read)在这里使用.
2)当您为字符串分配足够的内存时,您不会将它们终止.您可以calloc()将分配的整个内存清零.因为,你会立即写入其中,我宁愿使用malloc()而不是无谓地与归零calloc(),并与循环之后0终止字符串:
for(j = 0; j < t; j++){
string[pos][j] = read[i-(t-j)];
}
string[pos][j] = 0; // 0 terminates the string.
Run Code Online (Sandbox Code Playgroud)
PS:sizeof(char)总是1.
| 归档时间: |
|
| 查看次数: |
770 次 |
| 最近记录: |