简体   繁体   English

这个简单的C代码有什么问题?

[英]What's wrong with this simple C code?

#include <stdio.h>

int main()
{
    int m,n; scanf("%d %d",&m,&n);
    char ar[m][n];
    char buf[n];
    int a,b;
    for(a=0;a<m;a++)
    {
        gets(buf);
        for(b=0;b<n;b++) ar[a][b] = buf[b];
    }
    for(a=0;a<m;a++,printf("\n")) for(b=0;b<n;b++) printf("%c",ar[a][b]);
    return 0;
}

This code takes m lines as input from stdin , each line containing n characters, and prints all the lines to stdout . 此代码将m行作为来自stdin ,每行包含n个字符,并将所有行打印到stdout Simple as that. 就那么简单。 But there seems to be a memory leak, because the first time gets(buf) is encountered, its execution is skipped. 但是似乎有内存泄漏,因为第一次gets(buf)时,将跳过其执行。

I tried it in C++ too, thinking the memory leak will disappear. 我也在C ++中尝试过,认为内存泄漏将消失。 Here is the code: 这是代码:

#include <cstdio>
using namespace std;

int main()
{
    int m,n; scanf("%d %d",&m,&n);
    char **ar = new char*[m];
    char *buf = new char[n];
    int a,b;
    for(a=0;a<m;a++)
    {
        gets(buf);
        ar[a] = new char[n];
        for(b=0;b<n;b++) ar[a][b] = buf[b];
    }
    for(a=0;a<m;a++,printf("\n")) for(b=0;b<n;b++) printf("%c",ar[a][b]);
    return 0;
}

But it is behaving exactly the same. 但它的行为完全相同。

Here is some sample input and output: 这是一些示例输入和输出:

2 3
abc
def

output: 输出:

x��
abc

GDB doesn't seem to show anything up too. GDB似乎也没有显示任何内容。 Please help.. 请帮忙..

It's not a "memory leak". 这不是“内存泄漏”。 The problem is that the first gets() call reads the newline from when you enter the two dimensions on the first line; 问题在于,第一个gets()调用从您在第一行中输入两个维度时开始读取换行符。 it puts zero characters into the buffer, but you print 5, which is why you get a line of garbage. 它将零个字符放入缓冲区,但是您输出5,这就是为什么会出现一行垃圾的原因。

Add a "\\n" at the end of the scanf() format string so scanf() consumes the newline, and your program will work perfectly. scanf()格式字符串的末尾添加“ \\ n”,以便scanf()使用换行符,并且您的程序将正常运行。 Note that gets() is terribly unsafe; 注意, gets()非常不安全; using fgets(buf, n, stdin) is much preferred. 最好使用fgets(buf, n, stdin)

In addition to missing '\\n' in scanf() you should allocate more space for buf : 除了在scanf()缺少'\\n' ,您还应该为buf分配更多空间:

Example

#include <stdio.h>
#include <stdlib.h>

int main()
{
    int m,n; 
    if(scanf("%d%d\n",&m,&n) != 2)
        exit(EXIT_FAILURE);
    char ar[m][n];
    char buf[n+2]; // '\n\0'
    int a,b;
    for(a=0;a<m;a++)
    {
        if (!fgets(buf, n+2, stdin)) exit(EXIT_FAILURE);
        for(b=0;b<n;b++) ar[a][b] = buf[b];
    }
    for(a=0;a<m;a++,printf("\n")) for(b=0;b<n;b++) printf("%c",ar[a][b]);
    return 0;
}

Output 输出量

abc
def

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM