#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 soscanf()consumes the newline, and your program will work perfectly. Note thatgets()is terribly unsafe; usingfgets(buf, n, stdin)is much preferred.