Sahashoo
Sahashoo

Reputation: 23

C++ compile problem with strlen and strcpy

#include<iostream>
using namespace std;

int main()
{
    char a[5],b[5];
    cout<<strlen(a)<<endl;
    strcpy(a,b);
}

when I compile the code using g++ filename.cpp the code will be compiled with no issues but when my friends try to do it using dev-c++, they'll get errors!

based on cplusplus.com, I am the one who should get errors!!

so I am just wondering what's causing the difference here?

P.S: I have tried different versions of C++ using -std=c++98 throw -std=c++2a

Upvotes: 2

Views: 333

Answers (2)

Jesper Juhl
Jesper Juhl

Reputation: 31474

char a[5],b[5];
cout<<strlen(a)<<endl;
strcpy(a,b);

Both a and b are uninitialised. Your program has undefined behaviour. The compiler has no obligation to generate anything in particular. Any behaviour is acceptable. You cannot reason about code with UB. The program is simply invalid/broken (and the compiler is also not obligated to warn you about UB btw).

As for failing to compile: you did not include the header defining strcpy and strlen. That's in <cstring>. Include that header and the code should compile (it'll still be broken, but it should compile)..

Standard library headers (like iostream) are allowed to include other headers, but they are not required to do so. So, on some systems you may be able to get away with not including a header since some other one pulls it in for you. But that's not guaranteed and you shouldn't rely on it. Always explicitly include the headers for the stuff you need/use.

Upvotes: 3

IlCapitano
IlCapitano

Reputation: 2084

strlen and strcpy are declared in the <cstring> header. Some standard library implementations might include that in <iostream>, some might not. This explains why it may compile with some setups and not others.

Upvotes: 7

Related Questions