-1

I am new in C and tried checking the loop condition as to find on the internet, but I get this error I am not able to solve (no other questions/answers were helpful):

void main() {

char* insert = malloc(30);

printf("Insert a Molecular Formula:\n");
gets(insert);

if (insert) {
    for (int i = 0; insert[i] != '\0'; i++) {
    }
} }

I get the error 6011 in VS inside the for-loop when checking insert[i] != '\0'. I haven't found a good fix, I have tried cheking return of malloc like if(!insert){ //above code here} but this didn't help. Thanks in advance.

Tim
  • 3
  • 3
  • 1
    Never head of "error 6011". We need more information. Read this: [ask] and this: [mcve]. Also [beware of `gets`](https://stackoverflow.com/questions/1694036/why-is-the-gets-function-so-dangerous-that-it-should-not-be-used) – Jabberwocky Mar 29 '21 at 14:36
  • 1
    When asking questions about build errors, always include a [mcve] and the actual errors themselves (copy-pasted in full and complete, as text). – Some programmer dude Mar 29 '21 at 14:36
  • @Jabberwocky this is an error of potentially dereferencing null pointer. – SergeyA Mar 29 '21 at 14:36
  • 1
    Is that a compiler error or runtime error? Seems more like it would be a runtime error because of the null terminator – Irelia Mar 29 '21 at 14:37
  • 1
    You do not check the return value of `malloc` in the snippet provided, and MSVC gives you a warning because of that. If you still see the same warning after checking for return value, edit your question to include the snippet which checks for it. – SergeyA Mar 29 '21 at 14:37
  • Building a little bit on what @SergeyA has commented, even if you think you have checked the value, the check you comment `if (!insert) { //above code here }` is the opposite of what you want to do, because then your code would execute if malloc fails and returns NULL. – Ion Larrañaga Mar 29 '21 at 14:56
  • @IonLarrañaga, thank you, I found the logical mistake. Probably my checking was wrong before, now it works. – Tim Mar 29 '21 at 15:10

1 Answers1

0

Error C6011 is a warning, not an error, so your code will run, but it's not bad to handle these issues if Visual Studio is indicating them.

To get the warning to go away, fix your loop like so:

if (insert)
{
    for (int i = 0; insert[i] != '\0'; i++) {
    }
}
Visual Studio
  • 184
  • 1
  • 10
  • about the casting: I have found both opinions, to do and not to do this. I read it could hide errors/warnings. So what is best practice? – Tim Mar 29 '21 at 15:16
  • 1
    [Do I cast the result of malloc?](https://stackoverflow.com/q/605845/10871073) – Adrian Mole Mar 29 '21 at 15:29