I recently wrote a simple program to reverse a string, my program simply accepts an input string from user and then reverses it. This is all done with 2 pointers. Concerning the pointer safety in my program I wrote a function to duplicate the give string, This function allocates memory for a new (same length) string, and then copy the character 1-by-1.
My problem is when I run this program, Although It does what I need, It prints some mysterious extra output. It does this every time, before accepting input from the user. This is what happens when I run the program.
C:\Users\0xEDD1E\Desktop\revstr>revstr.exe
[C]
[.]
[revstr.exe]
hello
[hello]
olleh
here the last three lines are Input and Output, It's OK, The problem is in the first 3 lines
[C]
[.]
[revstr]
What are those? any way, here is my program
#include <stdio.h>
#include <stdlib.h>
#define swap(a, b) (((a) ^ (b)) && ((a) ^= (b), (b) ^= (a), (a) ^= (b)))
unsigned long strlen_(char *);
char *strdup(char *s);
char *reverseString(char *, int);
int main(void)
{
//fflush(stdout);
char *str = (char *) malloc(1024 * sizeof (char));
scanf("%[^\n]s", str);
int slen = strlen_(str);
printf("%s\n", reverseString(str, slen));
return 0;
}
unsigned long strlen_(char *s)
{
char *p = s;
while (*p) p++;
return p - s;
}
char *strdup(char *s)
{
char *p = (char *) malloc((size_t) (strlen_(s) + 1) * sizeof (char));
if (p) {
char *pp = p;
while ((*pp++ = *s++)) ;
}
printf("[%s]\n", p);
return p;
}
char* reverseString(char* s, int n)
{
char *str = strdup(s);
char *p = str - 1;
char *q = str + n;
while (++p < --q) {
swap(*p, *q);
}
return str;
}
you can see, looking at, strdup()
function, those lines are generated by the printf()
in the strdup()
function (because of printf("[%s]\n, str);
).
So I think I found the bug-point. But I can't figure out the reason for this error, and a way to fix it. Especially This happens only on Windows (mine is Windows 10 Pro). I tested this on Ubuntu(64bit), there is no bug like this in Ubuntu.
My instinct says me this error has to do something with pointers used in the functions
UPDATE: I tried fflush(stdout)
but that didn't help
What is the reason behind this Bug (or misbehave), could someone explain the reason?