I wanted to access the array elements using the struct attributes. I am able to print 1st and the 2nd element using the struct pointer (nameptr) while the remaining 3 elements has to be accessed using the (uint8_t ptr) which itself is a attribute of the 'struct name'.
#include <iostream>
struct name{
uint8_t b0;
uint8_t b1;
uint8_t* ptr;
}*nameptr;
int main()
{
uint8_t arr[]= {1,2,3,4,5};
nameptr = (name *)arr;
nameptr->ptr = arr+2;
printf("%d ", nameptr->b0); //prints 1
printf("%d ", nameptr->b1); //prints 2
for (int i=2; i<5; i++){
printf("%d ",*(nameptr->ptr+i)); //expecting to print 3 4 5
}
return 0;
}
When compiled I get the below error, Please help me getting this error solved.
*** stack smashing detected ***: ./a.out terminated
1 2 5 0 56 Aborted (core dumped)
This answer is based on the modified code as in revision 6 of the question.
If you have a structure of type name
, not only a pointer, you can assign the array address to the pointer element ptr
like this.
#include <cstdio>
#include <cstdint>
struct name{
uint8_t b0;
uint8_t b1;
uint8_t* ptr;
}*nameptr;
int main()
{
uint8_t arr[]= {1,2,3,4,5};
name name_struct; // actual memory where you can access the structure fields
nameptr = &name_struct; // pointer now points to a real structure of the correct type
nameptr->ptr = arr; // assign array to pointer inside structure
/* For this loop you must know the size of the array the pointer is pointing to.
* Your code cannot automatically derive this information from the
* pointer element `ptr` or from the structure like you could with
* sizeof(arr)/sizeof(arr[0]). */
for (int i=2; i<5; i++){
printf("%d ",*(nameptr->ptr+i)); //expecting to print 3 4 5
// printf("%d ",nameptr->ptr[i]); // same, but easier to understand
}
return 0;
}
The code in revision 7 of the question is wrong in several ways:
struct name{
uint8_t b0;
uint8_t b1;
uint8_t* ptr;
}*nameptr;
/* Depending on your platform, the structure might be something like this */
struct name_with_padding {
uint8_t b0; // 1st byte
uint8_t b1; // 2nd byte
// uint8_t padding[2]; // 3rd and 4th byte
uint8_t* ptr; // 5th to 8th byte
}*nameptr;
uint8_t arr[]= {1,2,3,4,5};
/* This cast is the main error. It will interpret the memory of the array
* as a structure as shown above which is undefined behavior (and
* implementation dependent).
* It might result in:
* b0 = 1
* b1 = 2
* padding = {3, 4}
* ptr = value 5 + some (3) bytes after it
* But it may as well result in other (undefined) behavior.
*/
nameptr = (name *)arr;
/* This may (depending on your implementation) overwrite
* overwrite the value 5 and the following (3) bytes
* with the address arr+2
* so it will change the value of arr[4] and the memory after it
* This may (or may not) result in a segmentation fauult or stack corruption.
*/
nameptr->ptr = arr+2;
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments