简体   繁体   中英

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 . Simple as that. But there seems to be a memory leak, because the first time gets(buf) is encountered, its execution is skipped.

I tried it in C++ too, thinking the memory leak will disappear. 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. 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; it puts zero characters into the buffer, but you print 5, which is why you get a line of garbage.

Add a "\\n" at the end of the scanf() format string so scanf() consumes the newline, and your program will work perfectly. Note that gets() is terribly unsafe; using fgets(buf, n, stdin) is much preferred.

In addition to missing '\\n' in scanf() you should allocate more space for 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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