Why do I get segfaults when declaring a structure globally or extern?

I have a structure defined in the header as follows:

#define LC_ERR_LEN 300
typedef struct dLC_ERRMSG {
   short nr;
   short strategy;
   char tx[LC_ERR_LEN];
} LC_ERRMSG;

What I use in my code as such:

LC_ERRMSG err;
char *szError;
szError = strerror(sStatus);
snprintf(err.tx,LC_ERR_LEN," %s - %s",szFilename,szError);
/* do something with our error string */

It works. If, however, I declare LC_ERRMSG err;globally - that is, outside the function used, or even extern LC_ERRMSG err;(this was my original intention, since I would like to be able to read the error status in a central place), the segfaults code when calling snprintf.

Can you give me any hints?

ddd tells me that the memory is initialized either with all zeros declared globally, or at least initialized and read when the extern is declared. The values ​​szFilename, szError, and LC_ERR_LEN are valid and significant.

+5
3
+3

:

// structs.hpp
#define LC_ERR_LEN 300
typedef struct dLC_ERRMSG {
    short nr;
    short strategy;
    char tx[LC_ERR_LEN];
} LC_ERRMSG;

// main.cpp
#include "structs.hpp"
LC_ERRMSG err;

int main()
{
    // ...

    char *szError;
    szError = strerror(sStatus);
    snprintf(err.tx, LC_ERR_LEN, "%s - %s", szFilename, szError);
}

. , main.cpp :

extern LC_ERRMSG err;

, err . , :

// globals.cpp
#include "structs.hpp"

LC_ERRMSG err;

globals.o main.o.

. , , LC_ERR_LEN , globals.cpp , main.cpp. , , szFilename szError NULL/bad. printf NULL %s; :

#include <stdio.h>

int main()
{
    printf("%s\n", NULL);
}

EDIT: . , C, err - , . ++, , err . , ++.

+2

+1 for Daniel's answer. Here is "Work for me." Does it work for you? Answer Upvote Daniel.


// structs.hpp
#define LC_ERR_LEN 300
typedef struct dLC_ERRMSG {
    short nr;
    short strategy;
    char tx[LC_ERR_LEN];
} LC_ERRMSG;

// error.cpp
#include "structs.hpp"

LC_ERRMSG err;

// main.cpp
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include "structs.hpp"
extern LC_ERRMSG err;

int main()
{
    // ...
    char *szFilename = "EXAMPLE.LOG";
    int sStatus = 0;
    char *szError;
    szError = strerror(sStatus);
    snprintf(err.tx, LC_ERR_LEN, "%s - %s", szFilename, szError);

    printf( "err.tx: %s", err.tx );
}

// Output:
err.tx: EXAMPLE.LOG - No error
+2
source

All Articles