0

I have a struct like this:

typedef struct
{
    char    private_key[ PRIVATE_KEY_SIZE ];
    char    certificate[ CERTIFICATE_SIZE ];
    uint8_t cooee_key  [ COOEE_KEY_SIZE ];
} platform_dct_security_t;

In my main function, I declared my variable:

platform_dct_security_t* dct_security = NULL;

Now I need to fill the arrays in this struct.

I also have my certificate defined like this:

#define CERTIFICATE_STRING  \
"-----BEGIN CERTIFICATE-----\r\n"\
"MIIFIzCCBAugAwIBAgIETB0zITANBgkqhkiG9w0BAQUFADCBsTELMAkGA1UE\r\n"\

                        ...
                        ...

"uhZ2VrLWSJLyi6Y+t6xcaeoLP2ZFuQ==\r\n"\
"-----END CERTIFICATE-----\r\n"\
"\0"\
"\0"

So I proceeded:

memcpy( dct_security->certificate, CERTIFICATE_STRING, CERTIFICATE_SIZE );
printf( "\n%s\n", dct_security->certificate );

However, this prints out something garbage. I also tried this but it didn't work either:

(*dct_security) = { CERTIFICATE_STRING, PRIVATE_KEY_STRING, COOEE_KEY_STRING };

When I compile and run with this, it doesn't crash but it gets stuck and nothing is printed out.

If I define another char array without having a struct, it works like a charm:

char xyz[ CERTIFICATE_SIZE ];
memcpy( xyz, CERTIFICATE_STRING, CERTIFICATE_SIZE );
printf("\n%s\n", xyz);

Where am I going wrong? How do I fix this?

Motun
  • 2,149
  • 3
  • 16
  • 23
  • 5
    You do make the pointer variable `dct_security` actually point somewhere valid? Can you please create a [Minimal, Complete, and Verifiable Example](http://stackoverflow.com/help/mcve) and show us? – Some programmer dude Aug 11 '16 at 12:36
  • 1
    What @JoachimPileborg means is: Did you allocated any memory for the pointer(e.g. with `malloc`) or initialized it somewhere else? – ckruczek Aug 11 '16 at 12:37
  • `dct_security` is not a variable of type `platform_dct_security_t`! Provide a [mcve] – too honest for this site Aug 11 '16 at 12:42
  • @JoachimPileborg @ckruczek Thank you very much, it appears that's what I was missing. Instead of initializing it with `NULL`, I used `malloc()` and it now works. I'm not sure if I got the logic behind this, though. – Motun Aug 11 '16 at 12:50
  • 2
    @Motun It seems you might need to pick up [a beginners book](http://stackoverflow.com/questions/562303/the-definitive-c-book-guide-and-list) and revisit the chapters on pointers. – Some programmer dude Aug 11 '16 at 13:24

1 Answers1

0

As Joachim Pileborg and ckruczek made me realize, I needed to allocate some memory for dct_security. So this change fixed the problem:

platform_dct_security_t* dct_security;
dct_security = malloc(sizeof(platform_dct_security_t));
Community
  • 1
  • 1
Motun
  • 2,149
  • 3
  • 16
  • 23
  • don't cast the result of `malloc`. also you should not use the `(char *)` cast in the other part of your code. Try to avoid using casts unless there is no alternative. – M.M Aug 11 '16 at 14:13