Search code examples
cpointersstructstackunions

C : assign value to uninitialzed struct and union


I am given two global variables, in pointer. All I need to do is assign character value to some local variables checking boundaries.

// global variable
char *min_ptr, *max_ptr ;

void markchar( char *x, int size, char marked) 
{
    // for every byte of x to have the value marked
    int num_arr_elem = size/sizeof(char);
    for (int i=0; i<num_arr_elem; i++) {
        x[i] = marked;
    }

}

And I assign like the following: Is it correct? I am now so confused. How do I check the boundaries with the global min and max pointer? How do I assign anything to struct and union and array that are not initialized? They are all null and zeros by default? But seems like I keep getting errors doing the following.

I need to do this to see later what part of stack is not assigned any value between max and min pointers... so I need to somehow check some values below are between those boundaries, but they are not even initialized so how do I check anything?

is this correct?

int i ;
markchar( (char *) &i, sizeof(i), 0xa1 )

is this correct?

struct sss {
    char* a ;
    char b[20] ;
    float c ;
} s;
markchar( (char *) &s, sizeof(s), 0xb1 )

is this correct?

union ccc {
    float a ;
    char b ;
    int c ;
} u ;
markchar( (char *) &u, sizeof(u), 0xc1 )

is this correct?

char aa[50] ;
markchar( (char *) &aa, sizeof(aa), 0xd1 )

I would greatly appreciate it. I am so lost right now. Spend so many hours trying to figure this out.


Solution

  • First of all there is a lot of redundant code in your example.

    int num_arr_elem = size/sizeof(char);
    

    You don't have to divide by sizeof(char) as sizeof char is guaranteed to be always 1.

    In the example

    char aa[50] ;
    markchar( (char *) &aa, sizeof(aa), 0xd1 )
    

    it also mistake to provide pointer to array as in C name is implicitly converted to pointer to the first element so markchar( aa, sizeof(aa), 0xd1 ) is enough.

    Regarding the initialization: if the value is global one is by default initialized to 0. If this is local it's left uninitialized so there are some garbage that variable is "initialized" to. If you want to fill any variable (no matter if this is ordinary one or srtuct or array) with given pattern you can use memset. Example related to your code could be:

    char marked;    
    memset(struct s, marked, sizeof(struct sss)); 
    

    You can also do this using using initializer, but this can be done only once just use:

    struct sss s = { 0 };