Home > Software engineering >  Which of the following operation can lead to illegal memory access
Which of the following operation can lead to illegal memory access

Time:01-08

Consider the following declaration of C code.

int (*p)[10];

If the variable is not initialized to any address then which of the following may give a run-time error?

  1. (p 1)
  2. (p 1)[2]
  3. p[2]
  4. *p[2]

My answer: 2, 3, 4.

As p is not initialized it can contain any garbage value, so *(p 3), *(p 2), and **(p 2) can lead to illegal memory access.

Given answer: 4.

Their explanation: We get a runtime error (segmentation fault) if we try to access some invalid memory. is a pointer to an integer array of size Its declaration has one * (star) and one [ ] (square bracket). If we want to access memory using then we have to use Either two * (stars) Or one * (star) and one [ ] (square bracket) Or two [ ] (square bracket)

Following usages might give runtime errors -

**p
*p[]
p[][]

can 2 and 3 lead to illegal memory accesses?

CodePudding user response:

Generally none and all of them. Everything depends on how you use it.

Exmaples:

  1. If you use it in sizeof it is safe
    printf("%zu\n",sizeof((p 1)));
    printf("%zu\n",sizeof(((p 1)[2])));
    printf("%zu\n",sizeof((p[2])));
    printf("%zu\n",sizeof((*p[2])));

2.Any of them can lead to the Undefined Behaviour (which can express itself as memory fault)

    p = (p 1);  //UB is p is dereferenced
    int *x = (p 1)[2]; //x has undermined value
    int *y = p[2];     //same as above
    *p[2] = 5;         //p was not initialized  
  • Related