0

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.

Edited by rtyui

3
Contributors
2
Replies
3
Views
5 Years
Discussion Span
Last Post by deceptikon
0

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;
    }
}
This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.