Hi. I am trying to assign the value returned by asctime(struct tm *) to a string. But when the program is run, I got segmentation fault. GDB shows:

Program received signal SIGSEGV, Segmentation fault.
0x0000003e6d6aa192 in __offtime () from /lib64/libc.so.6

What could be the reason? Can't we assign the value returned by asctime() to a string?

Thanks in advance.

Can you post your code, so that we can take a look at it? Thanks.

Can't we assign the value returned by asctime() to a string?

You can, but asctime() uses an internal buffer for the string, so it would be wise to make sure that a copy is made:

#include <cstring>
#include <ctime>
#include <iostream>
#include <string>

using namespace std;

int main()
{
    time_t now = time(0);

    // Using a std::string (recommended)
    {
        string s = asctime(localtime(&now));

        cout << s;
    }

    // Using a C-style string
    {
        char *p = new char[50]; // Plenty of room

        strcpy(p, asctime(localtime(&now)));
        cout << p;

        delete[] p;
    }
}
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.