How do I 'dive' an int * which points to a dynamically allocated array of integers and represent it as a fixed int[] array? Put otherwise, if I dive an int * it shows the address and the int pointed to, but instead I would like to see the array of all of the integers.
I noticed the TotalView tag on this question. Are you asking how to see the values in your array in totalview? If so then the answer is pretty easy.
Lets say you have a pointer p which is of type int * and you have it currently pointing towards an array with 10 integers.
Step 1. Dive on the pointer. That's accomplished by double clicking, clicking the middle mouse button, or using the dive option on the context menu -- all after having placed the mouse cursor on the variable int he source code pane or the stack frame pane.
This will bring up a new window that will say
Expression: p
Address: 0xbfaa1234
Type: int *
and down in the data area will say something like
0x08059199 -> 0x000001a5 (412)
This window is showing you the pointer itself, the address listed is the address of the pointer. The value (0x08059199 in the example above) is the actual value that the pointer has. Everything to the right of the arrow is just a "hint" telling you want it points to.
Step 2. Dive on the pointer again. Repeat the double click or middle mouse button, this time on the data value in the variable window. (So you are double clicking where it says 0x08059199).
This will effectively "dereference" the pointer. Now the window is focused not on pointer itself but the thing that the pointer pointed to. Notice that the address box now contains 0x08059199 which was the value before.
expression: *(((int *) p))
Address: 0x08059199
Type: int
and down in the data area it will say something like
0x000001a5 (412)
Step 3. Cast the data window to the type you want. Just click in the type field and change it to say int[10]. Then hit return.
This tells the debugger that 0x08059199 is the beginning of an array of 10 integers.
The window will grow two new fields: Slice and Filter. You can leave those alone for now, but they can be useful later.
The data area will now show two columns "field" and "value" and 10 rows.
The field column will be the index in the array [0] - [9] and the value column will tell you what data you have in each array location.
Other tips:
In more complicated data structures you can may want to dive on individual elements (which might also be pointers, diving will dereference them as well)
You can always cast to different types or lengths to look at data "as if it was" whatever
You can edit the actual data values by clicking on the value column and editing what you find there. This is useful when you want to provoke specific mis-behavior from your application
You can always undo diving operations with the "<" icon in the upper right hand corner of the variable window.
There are some online videos that you might find helpful at
http://www.roguewave.com/products/totalview/resources/videos.aspx
in particular there is one labeled "getting started with TotalView".
Don't hesitate to contact us at Rogue Wave Software for TotalView usage tips!
support at roguewave dot com is a good address for that.
Chris Gottbrath
(Chris dot Gottbrath at roguewave dot com)
TotalView Product Manager at Rogue Wave Software
It's not very hard, but i forgot how it exactly works. I found you a page which explains it tho ;). I think to point and array with ints called for example test you should get it using &test.
Just check this page out:
http://www.cplusplus.com/doc/tutorial/pointers/
You can't meaningfully do this without knowing exactly how many ints are in the array.
If you have an int *p that points to the first element in a contiguous int data, either dynamically allocated, or a static array, you can index it as if it were an array:
int *data = malloc(3 * sizeof *data);
int *p;
/* malloc error detection omitted for brevity */
data[0] = 1;
data[1] = 2;
data[3] = 42;
p = data;
assert(p[0] == 1);
assert(p[1] == 2);
assert(p[2] == 42);
You have to know the size of the valid data you are accessing this way.
So, let's say I have data as above, and want to write a function to print it. It won't do to declare the function like this:
void print_array(int *data);
because when you call print_array(data);, the function doesn't know the number of elements to print.
You could define your print_array() like:
void print_array(int *data, size_t n);
where n denotes the number of valid elements pointed to by data, that the caller has to supply. Or you could decide that every "array" will end with a sentinel value, a value that is used only at the end of the data, and is not useful value otherwise:
data[2] = 0; /* data[0] and data[1] are useful, valid values
and data[2] is 0 to signify the end of the data */
Then you can declare your print_array() as:
void print_array(int *data);
and keep indexing into data in the function definition till you hit a sentinel:
void print_array(int *data)
{
size_t i;
for (i=0; data[i] != 0; ++i)
printf("%d\n", data[i]);
}
So, to answer your question, you can already treat a pointer to a valid dynamically allocated data as an array. You have to remember the size of the allocated data of course, which you would need to do in a regular array too.
Related
I'm curious why the API ntquerysysteminformtion return size that is different from the sum of all nextEntryOffsets. I call the API with a SYSTEM_PROCESS_INFORMATION structure, and it returns the size of the struct populated as expected.
However if I loop into all entries and sum the NextEntryOffset and do a comparison with the size returned with the API it never mismatch.
//call to API
int sum = 0;
pCurrent = nullptr;
pfw = (_SYSTEM_PROCESS_INFORMATION*)si;
do {
pCurrent = pfw;
pfw = (_SYSTEM_PROCESS_INFORMATION*)((PUCHAR)pCurrent + pfw->NextEntryOffset);
sum += pCurrent->NextEntryOffset;
} while (pCurrent->NextEntryOffset != 0);
If I print the value of sum variable and length returned by API they are always not equal.
How to discover / calculate the correct size of each entry if there is no field on the structure for this? My guess is that it's not working because on the last entry the NextEntryOffset is null, but this is weird, because I dont see a way to calculate the real size of each entry without just believe on the returned length. I guess that there is a way, right?
I was reading unofficial documentation and it describe that the start of its output buffer and irregularly throughout the buffer when given specific information classes like mine. I don't understand how it work, but I assume that for example if there is an pointer to another structure this pointer size + the size of the data or other struct pointed is calculated as part of the total size which may be dynamically, correct?
I also tried see if the field offsets works as expected on this unoffical documentation, but I failed to access it contents. It work for example to see the supposed address of UniqueProcessId, however I can't find a way to see the value inside this address to confirm.
PVOID tmp = pCurrent + 0x50;
wprintf(L"ID: %d", *tmp);
It fails. I can call the structure like pCurrent.UniqueProcessId and it works. But how to move on the data without depends on the struct? Examples codes are very welcome.
Thank so much.
The loop looks correct. The size doesn't match because you can't measure the size of the last struct in the return buffer that way. What's going on is the structure is variable length. In modern C we would declare the last element as a flexible array of SYSTEM_THREAD_ENTRY (where the size is given in NumberOfThreads), but the stuff from NTDLL is old.
The "right" way to code it (in so far as there's any right) is to copy the data you need into your own datastructure then discard the original buffer.
The sum you get only calculates the length of the first to penultimate struct, which is not include the length of the last one. As other answer pointed out, this is a variable-length struct, Each struct is immediately followed in memory by one or more SYSTEM_THREAD_INFORMATION structures that provide info for each thread in the preceding process.
And there is also the memory space for the ImageName.Buffer(the size is determined by the system), you do not need to calculate the size of each struct yourself, first pass NULL to get the required size:
NtQuerySystemInformation(SystemProcessInformation, NULL, 0, &length);
If you want to know the size of the last structure, just use length-sum.
In addition, pCurrent + 0x50 is equal to &pCurrent[0x50], try to test wih (char*)pCurrent + 0x50.
For variable arrays, see https://devblogs.microsoft.com/oldnewthing/20040826-00/?p=38043
I want to stick 2D arrays in a 3D array together, first i defined the 3D array in the following way
int ***grid;
grid=new int **[number];
then I want to assign the 2D arrays to the 3D construct
for(i=0;i<number;i++)
grid[i]=rk4tillimpact2dens(...);
with
int** rk4tillimpact2dens(...
...
static int** grid;
grid=new int*[600];
for(i=0;i<600;i++)
grid[i]=new int[600];
memset(grid,0x0,sizeof(grid));
...
return(grid);
}
so far no problem, everything works fine, but when I want to access the 3D array afterwards I get a seg fault. Like that e.g.
printf("%d",grid[1][1][1]);
What is my mistake?
Best,
Hannes
Oh, sorry, it was typo in my question, I did
printf("%d",grid[1][1][1]);
it's not working :(. But even
printf("%d",&grid[1][1][1]);
or
printf("%d",*grid[1][1][1]);
would not work. The strange thing is, that there are no errors unless I try to access the array
First, you discard the very first row of each matrix with that memset (the actual row is leaked). While technically grid[1][1][1] should still be readable, it probably becomes corrupt in some other place.
Can you provide a minimal verifiable example? This is likely to solve your problem.
To clear out the memory allocated for grid, you can't do the whole NxN matrix with one memset, it isn't contiguous memory. Since each row is allocated as a separate memory block, you need to clear them individually.
for(i=0;i<600;i++) {
grid[i]=new int[600];
memset(grid[i], 0, sizeof(int) * 600);
}
The 600 value should be a named constant, and not a hardcoded number.
And grid does not need to be a static variable.
Printing out the address
printf("%p",&grid[1][1][1]);
You are printing the address here. That's why you may not get what you desire to see.
printf("%d",grid[1][1][1]);
This will print the array element.
And to read an input from stdin you will use scanf() which requires you to pass address of an variable.
scanf("%d",&grid[1][1][1]);
Zeroing out the allocated memory
Also you can't get the size of the array using sizeof. SO to initialize with 0 you use memset on the chunks that are allocated at once with a new.
In your case example would be Like 1201ProgramAlarm pointed out
for(int i = 0; i < 600; i++){
...
memset(grid[i],0,sizeof(int)*600);
}
There is another way you can initialise an allocated memory in c++.
grid[i]=new int[600]();
For example:
int** rk4tillimpact2dens(...
...
static int** grid;
grid=new int*[600];
for(i=0;i<600;i++)
grid[i]=new int[600]();
...
return(grid);
}
Do you expect memset(grid,0x0,sizeof(grid)); not to zero the pointer values you've just assigned to grid[0] through to grid[599]? If so, you should test that theory by inspecting the pointer values of grid[0] through to grid[599] before and after that call to memset, to find out what memset does to true (more on that later) arrays.
Your program is dereferencing a null pointer which results directly from that line of code. Typically, a crash can be expected when you attempt to dereference a null pointer, because null pointers don't reference any objects. This explains your observation of a crash, and your observation of the crash disappearing when you comment out that call to memset. You can't expect good things to happen if you try to use the value of something which isn't an object, such as grid[1][... where grid[1] is a pointer consisting entirely of zero bits.
The term 3D array doesn't mean what you think it means, by the way. Arrays in C and C++ are considered to be a single allocation, where-as what your code is producing seems to be multiple allocations, associated in a hierarchical form; you've allocated a tree as opposed to an array, and memset isn't appropriate to zero a tree. Perhaps your experiments could be better guided from this point on by a book regarding algorithms, such as Algorithms in C, parts 1-4 by Robert Sedgewick.
For the meantime, in C, the following will get you a pointer to a 2D array which you can mostly use as though it's a 3D array:
void *make_grid(size_t x, size_t y, size_t z) {
int (*grid)[y][z] = malloc(x * sizeof *grid);
/* XXX: use `grid` as though it's a 3D array here.
* i.e. grid[0][1][2] = 42;
*/
return grid;
}
Assuming make_grid returns something non-null, you can use a single call to memset to zero the entirety of the array pointed to by that function because there's a single call to malloc matching that a single call to memset... Otherwise, if you want to zero a tree, you'll probably want to call memset n times for n items.
In C++, I don't think you'll find many who discourage the use of std::vector in place of arrays. You might want to at least consider that option, as well as the other options you have (such as trees; it seems like you want to use a tree, which is fine because trees have perfectly appropriate usecases that arrays aren't valid for, and you haven't given us enough context to tell which would be most appropriate for you).
I'm trying to allocate a new array if integers (See HwGrades allocation below)
When I put the HwNum=2, the new function creates an array of size 1 only!
and when the for loop iterates 2 times it doesnt give me access violation
Help would be appreciated..
Here's the constructor
EE_Course::EE_Course(int Course_ID, char * Course_Name, int Hw_Num, double Hw_Weigh,int Factor_)
{
CourseID = Course_ID;
CourseName = new char[strlen(Course_Name) + 1];
strcpy(CourseName, Course_Name);
HwNum = Hw_Num;
HwWeigh = Hw_Weigh;
HwGrades = new int [HwNum]; // STARTING FROM HERE
for (int i = 0; i < Hw_Num; i++) { //UNTIL HERE
HwGrades[i] = 0;
}
Factor_ = 0;
ExamGrade = 0;
}
And those are the Course class private variables :
protected:
int CourseID;
int HwNum;
char* CourseName;
double HwWeigh;
int ExamGrade;
int* HwGrades;
};
The debugger does not show the whole array if it is a pointer. It shows the address of the array and the first element the array is pointing. So there is nothing wrong with your code.
You could see it if it was defined as an array:
int HwGrades[100];
If you really want to use a pointer and see it's content, you have two choices:
Define it as an array, debug it, fix/verify your code and turn back to pointer.
I don't know what is you environment, but usually there is a memory view option. You can check what's in the array any time you want. Just open the memory view of your IDE and watch the address of your pointer.
EDIT:
Apparently there is a third(and the best) option. See Rabbi Shuki's answer.
The debugger just shows one element. Here's why:
The type of HwGrades is int*. So when showing the contents of HwGrades what should the debugger do? The debugger does not know, that the pointer is actually pointing to the first element of an array. It assumes it just points to an int. Therefore, the debugger shows just the first element of the array that is actually of size 2.
If you're using the Visual Studio debugger, you can write HwGrades,2 in the watch window to see the first two elements of the array. Replace 2 by whatever your tickles your fancy. ;)
However, generally I would strongly advice to use the STL container std::vector for dynamic arrays. It will be easier to program and the debugger will be your friend without the hassle.
If you want to see the next cells of the array in the watch screen you can put the name and add a comma and the number of cells you want to see.
I.E.
HwGrades, 2
I have a large char array which is functioning as a memory pool and want to store a pointer in the first position of the array which points to whatever the next open position in the pool is, so every time something is allocated to the pool the pointer would point to the byte that follows the ones which were just allocated. My only problem is I am not quite sure how to store the pointer in the array and then be able to modify it in other functions since the only place the pointer will exist is in the array[0] position. Can anyone point me in the right direction on this?
the char array is declared like:
char pool[size];
What you really want is an index into that array that tells you where to insert.
You could declare a structure:
struct pool
{
char poolData[size];
int insertIndex;
};
So that you always have the pool memory and index where you want to insert to together. Or, just have a separate variable and pass them together to whoever needs to use it.
char pool[size];
int insertIndex;
There's no need to "hijack" the first element of the array and use it differently than the rest of the array; just declare another variable to track the state of the pool.
If you can't follow the recommendations of the other answers because you absolutely must use the pool to store all information in it, the safest way to store the integer information in the char-array is to use memcpy (I am using C++11 syntax):
#include <cstring>
#include <iostream>
int main()
{
using size_type = std::size_t;
static constexpr size_type size = 1000;
char pool[size];
/* Store 12 as integer information at the beginning
of the pool: */
size_type next_free = 12;
std::memcpy(pool,&next_free,sizeof(size_type));
/* Retrieve it: */
size_type retrieved = 0;
std::memcpy(&retrieved,pool,sizeof(size_type));
/* This will output 12: */
std::cout << retrieved << std::endl;
return 0;
}
Of course this implies that the first sizeof(size_type) entries of the pool must not be used to store any actual characters. The lowest entry you can actually use is pool[sizeof(size_type)].
I think what you need is an index to remember where is the next empty spot on the pool (initially will be zero).
char pool[size];
int index = 0;
Then everytime you insert a new element, you just increment it:
if(index < size) {
pool[index] = 123;
index++;
}
char **pPoolEnd = (char **) pool;
to initialize the pointer you want.
*pPoolEnd = pool + sizeof(char **);
to make it point to its own end (e.g. when there's nothing else in the pool).
However, why would you want to do this? It's confusing, error prone and probably unnecessary. Others have pointed to much better alternatives. Assuming I had such a pool in the first place, I would probably go with one of those, or simply use a separate pointer, char *poolEnd along with pool.
Also, it's bad style to expose your implementation details to users ("pool end pointer is at pool[0]") and even worse to expect them to deal with them ("please update pool[0] whenever you'd like to allocate from the pool"). Think malloc and free; expose simple function interfaces to your users.
I need to use a function (part of an API) which stores some requested data into a dynamic sized struct using call by reference. The struct is defined as follows - it concerns access control lists of either posix or NFS4 version, but that is just the use case, I guess.
typedef struct my_struct
{
unsigned int len; /* total length of the struct in bytes */
... /* some other static sized fields */
unsigned int version; /* 2 different versions are possible */
unsigned int amount; /* number of entries that follow */
union {
entry_v1_t entry_v1[1];
entry_v2_t entry_v2[1];
};
} my_struct_t;
There are 2 versions of the entries and I know which one I will obtain (v1). Both entry_v1_t and entry_v2_t are fixed (but different) sized structs just containing integers (so I guess they are not worth being explained here). Now I need to use an existing function to fill my structure with the information I need using Call by Reference, the signature is as follows, including the comments - I don't have access to the implementation:
int get_information(char *pathname, void *ptr);
/* The ptr parameter must point to a buffer mapped by the my_struct
* structure. The first four bytes of the buffer must contain its total size.
*/
So the point is, that I must allocate memory for that struct but don't know for how much entries (and, as consequence, the total size) I must allocate. Have you ever dealt with such a situation?
Under Windows API there are many such functions, you normally call them with some NULL pointer to get size of the buffer, then call again with allocated buffer. In case during next call size of buffer have changed function returns error and you need allocate again. So you do it in a while loop till function returns with success.
So your get_information must implement somehow such mechanisms, either it returns false if buffer is to small or returns its correct size if ptr is NULL. But that is just my guess.
OK I thing I figured out how it works. Thanks for your ideas and notes. I declared a my_struct pointer and allocated minimum space for the fixed sized fields (5) before the dynamic array => 5 * sizeof(unsigned int). Invoking get_information with that pointer returns -1 and sets errno = 28 and strerror(errno) = "No space left on device".
But, it sets the my_struct->len field to the required size and that seems to be the answer to my question - how should you know? No I can invoke get_information initially with the minimum space and figure out how much I need to allocate, and afterwards call it again with the right sized memory allocated to get the information successfully.
The loop solution seems to make sense anyway and would have been my next try - since there are usually just a few entries in that dynamic array.
Thank you.