0

Its a simple input that I want to make for char*. Why is this not working? It throws me an exception that I can't resolve..

#include "stdafx.h"
#include "stdio.h"
#include "stdlib.h"

char* GetCharSeq()
{
    char *s = (char*)malloc(100);

    scanf_s("%s", s);

    return s;
}

int main()
{
    char* charseq;

    charseq = GetCharSeq();

    return 0;
}
Dietmar Kühl
  • 150,225
  • 13
  • 225
  • 380
v.g.
  • 1,076
  • 5
  • 19
  • 38
  • 3
    Unrelated to your problem, but for system header files you should use angle-brackets like e.g. `#include `, and in C you [should not cast the result of `malloc`](http://stackoverflow.com/questions/605845/do-i-cast-the-result-of-malloc). – Some programmer dude Dec 11 '15 at 09:42
  • 1
    if you get an exception, it makes sense to post it aswell – hoijui Dec 11 '15 at 09:43
  • You should always check return codes (e.g. `scanf_s`'s). What is the actual exception? – CristiFati Dec 11 '15 at 09:43
  • @JoachimPileborg It might not be the real problem for his exception. And casting will not harm as well. – Anish Sharma Dec 11 '15 at 10:15
  • @AnishSharma The casting *can* do harm, that's the problem. Read the second point in the accepted answer. And it's definitely not the source of the problem here, for that I have added an answer (also note the starting disclaimer in the comment about it being unrelated to the problem). – Some programmer dude Dec 11 '15 at 10:24

2 Answers2

4

You have undefined behavior in your code. You have it because you provide to few arguments to the scanf_s function.

For every string argument, you need to provide not only the destination string but also the size of the string. So change your call to

scanf_s("%s", s, 100);
Some programmer dude
  • 400,186
  • 35
  • 402
  • 621
  • 1
    How does it compile/link with a mismatched parameter list? – Martin James Dec 11 '15 at 09:47
  • 4
    @MartinJames for the same reason `printf("%s");` will compile and link. – mch Dec 11 '15 at 09:49
  • @MartinJames Because the `...` in the prototype means there's a variable number of arguments, and the compiler has no way of knowing the exact amount. Some compilers can figure it out by parsing the format string and will give warnings for such problems, but it's just a warning and technically legal C. – Some programmer dude Dec 11 '15 at 09:54
  • `scanf_s()` will only compile on a PC. He should rather use `fgets()` as it is a single string he wants to receive. – Zach P Dec 11 '15 at 11:09
1

modify your code

char* GetCharSeq()
{
    char *s = (char*)malloc(100);

    gets(s);

    return s;
}

This will work.

Anish Sharma
  • 495
  • 3
  • 15