I'm new to C, so the answer might be obvious but I just can't get my head around it.
I'm trying to create C++ vector kind of structure in C. I use Windows EnumWindows function to loop through all the windows. In the callback function I create new instance of windowHandle -structure for each window. For some reason however it doesn't seem to create new instance but rather just overwrites the old one. Or maybe it creates new instance, but when I give value to attribute windowHandle->title, it applies that change to every instance of windowHandle?
Callback function:
BOOL CALLBACK delegate(HWND wnd, LPARAM param){
if (filter(wnd)){ //<- just to make sure it's kind of window that we want.
char windowName[256] = {};
GetWindowText(wnd, windowName, sizeof(windowName));
windowHandle *handle = malloc(sizeof(windowHandle)); //<- create new instance of windowHandle for each window
handle->hWND = wnd;
handle->title = windowName;
insert((windowArray*) param, handle); //<- insert each windowHandle in our 'vector'
}
// but return true here so that we iterate all windows
return TRUE;
}
Call to EnumWindows function:
windowArray* array = array_init(20);
EnumWindows(&delegate, (LPARAM) array); //<- not quite sure what that '&'-sign does?
Structures:
typedef struct windowHandle{
HWND hWND;
char* title;
} windowHandle;
typedef struct windowArray{
int count;
int capacity;
int objectSize;
windowHandle* windows;
} windowArray;
And lastly insert:
int insert(windowArray* array, void* handle){
int index = (array->count * array->objectSize);
if(index > 0){
printf("\n%s %s\n", "first element's title is: ", array->windows->title); //<- prints to see if new handle overwrite the previous ones
}
printf("%s %s %s %p %s %d\n", "Inserted element ", ((windowHandle*)handle)->title, " with pointer ", handle, " on index ", index);
fflush(stdout); //<- prints info about first & current window
memcpy(array->windows + (index), (windowHandle*)handle, array->objectSize);
array->count++;
}
Output during insert calls:
Inserted element joo - Java - nativeWindowCapture/src/NativeWindowHookImp.c - Eclipse SDK with pointer 0000000000FB1B90 on index 0
first element's title is: Komentokehote
Inserted element Komentokehote with pointer 0000000000FB1BB0 on index 16
first element's title is: C struct instance overwrites previous instance - Stack Overflow - Mozilla Firefox
Inserted element C struct instance overwrites previous instance - Stack Overflow - Mozilla Firefox with pointer 0000000000FB1BD0 on index 32
first element's title is: JNI compiler kutsu – Muistio
Inserted element JNI compiler kutsu – Muistio with pointer 0000000000FB1BF0 on index 48
first element's title is: Skype™?
Inserted element Skype™? with pointer 0000000000FB1C10 on index 64
first element's title is: eclipse
Inserted element eclipse with pointer 0000000000FB1C30 on index 80
first element's title is: src
Inserted element src with pointer 0000000000FBCCE0 on index 96
all added
and then if I print the full content of windowArray->windows, I get the following results:
Getting value src , at index 0 and pointer 0000000000FBBB80
Getting value src , at index 16 and pointer 0000000000FBBC80
Getting value src , at index 32 and pointer 0000000000FBBD80
Getting value src , at index 48 and pointer 0000000000FBBE80
Getting value src , at index 64 and pointer 0000000000FBBF80
Getting value src , at index 80 and pointer 0000000000FBC080
Getting value src , at index 96 and pointer 0000000000FBC180
P.S. I would also like to know why windowArray's windows-attribute's pointers are different from those of *handle-objects created in delegate? That doesn't seem to be very efficient memorywise?
You set handle->title to point to windowName. But as soon as you exit this scope, windowName will cease to exist. So your structure contains a pointer to an array that no longer exists.
char windowName[256] = {};
GetWindowText(wnd, windowName, sizeof(windowName));
windowHandle *handle = malloc(sizeof(windowHandle)); //<- create new instance of windowHandle for each window
handle->hWND = wnd;
handle->title = windowName;
}
// when we get here, windowName ceases to exist
// so why did we store a pointer to it?
After you exit the scope, it is an error to follow the title pointer, since it no longer points to any object that is still alive. Perhaps change title from char * to char[256].
Related
I'm having problems enumerating function names in kernel32.dll. I retrieved its IMAGE_EXPORT_DIRECTORY structure and stored an array of pointers to char arrays of each function name: char** name_table = (char**)(image+pExp_dir->AddressOfNames); //pExp_dir is a pointer to the IMAGE_EXPORT_DIRECTORY structure. I'm now trying to iterate through the function names and match them to a string containing the name of the function whom's RVA I need.
for(int i=0;i<pExp_dir->NumberOfNames;i++) //until i is 1 less than how many names there are to iterate through elements
{
printf("%s ", (char*)(image+(DWORD)(uintptr_t)name_table[i])); //print the name of each function iterated through, I went back and read through these names and didn't see GetProcAddress anywhere
if(proc_name == image+(DWORD)(uintptr_t)name_table[i]) //if(strcmp(proc_name, (const char*)image+(DWORD)(intptr_t)name_table[i]) == 0) //Is it the function we're looking for?
{
address = (DWORD)(uintptr_t)func_table[ord_table[i]];//If so convert the address of the function into a DWORD(hexadecimal)
system("pause");
system("CLS"); //Clear the screen
return address; //return the address of the function
}
But if it doesn't find the function then the program crashes. And after looking in the memory dump in the DBG debugger I can see that name_tables contains all of the function names including the function I'm looking for but my program seems to skip several elements even though I'm iterating through its elements one at a time. User stijn suggested that I shouldn't use intptr_t to cast char* to DWORD to use for pointer arithmetic. So my question is really about the correct way to iterate through name_table because it seems as if this is a pointer arithmetic problem. Here's the function to get the file image and the function that actually gets the RVA:
void* GetFileImage(char path[]) //Get maps the image of the file into memory and returns the beginning virtual address of the file in memory
{
HANDLE hFile = CreateFile(path, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_READONLY, NULL);//Get a handle to the dll with read rights
if(hFile == INVALID_HANDLE_VALUE){printf("Error getting file handle: %d", (int)GetLastError());return NULL;} //Check whether or not CreateFile succeeded
HANDLE file_map = CreateFileMapping(hFile, NULL, PAGE_READONLY|SEC_IMAGE, 0, 0, "KernelMap"); //Create file map
if(file_map == INVALID_HANDLE_VALUE){printf("Error mapping file: %d", (int)GetLastError());return NULL;} //Did it succeed
LPVOID file_image = MapViewOfFile(file_map, FILE_MAP_READ, 0, 0, 0); //Map it into the virtual address space of my program
if(file_image == 0){printf("Error getting mapped view: %d", (int)GetLastError());return NULL;} //Did it succeed
return file_image; //return the base address of the image
}
DWORD RVAddress(char* image, const char* proc_name) //Gets the relative virtual address of the function and returns a DWORD to be cast to void*.
{
DWORD address = 0xFFFFFFFF;
PIMAGE_DOS_HEADER pDos_hdr = (PIMAGE_DOS_HEADER)image; //Get dos header
PIMAGE_NT_HEADERS pNt_hdr = (PIMAGE_NT_HEADERS)(image+pDos_hdr->e_lfanew); //Get PE header by using the offset in dos header + the base address of the file image
IMAGE_OPTIONAL_HEADER opt_hdr = pNt_hdr->OptionalHeader; //Get the optional header
IMAGE_DATA_DIRECTORY exp_entry = opt_hdr.DataDirectory[IMAGE_DIRECTORY_ENTRY_EXPORT];
PIMAGE_EXPORT_DIRECTORY pExp_dir = (PIMAGE_EXPORT_DIRECTORY)(image+exp_entry.VirtualAddress); //Get a pointer to the export directory
void** func_table = (void**)(image+pExp_dir->AddressOfFunctions); //Get an array of pointers to the functions
WORD* ord_table = (WORD*)(image+pExp_dir->AddressOfNameOrdinals); //Get an array of ordinals
char** name_table = (char**)(image+pExp_dir->AddressOfNames); //Get an array of function names
for(int i=0;i<pExp_dir->NumberOfNames;i++) //until i is 1 less than how many names there are to iterate through elements
{
printf("%s ", (char*)(image+(DWORD)(uintptr_t)name_table[i])); //print the name of each function iterated through, I went back and read through these names and didn't see GetProcAddress anywhere
if(proc_name == image+(DWORD)(uintptr_t)name_table[i]) //if(strcmp(proc_name, (const char*)image+(DWORD)(intptr_t)name_table[i]) == 0) //Is it the function we're looking for?
{
address = (DWORD)(uintptr_t)func_table[ord_table[i]];//If so convert the address of the function into a DWORD(hexadecimal)
system("pause");
system("CLS"); //Clear the screen
return address; //return the address of the function
}
}
return (DWORD)0; //Other wise return 0
}
Any help would be much appreciated!
Docs (Section 6.3) say next about AddressOfNames table
The Export Name Pointer Table is an array of addresses (RVAs) into the
Export Name Table. The pointers are 32 bits each and are relative to
the Image Base. The pointers are ordered lexically to allow binary
searches.
And about AddressOfFunctions:
Each entry in the Export Address Table is a field that uses one of two
formats, ... If the address specified is not within the export section
(as defined by the address and length indicated in the Optional
Header), the field is an Export RVA: an actual address in code or
data. Otherwise, the field is a Forwarder RVA, which names a symbol in
another DLL.
Your variables is not void** and char**, but actually all are DWORD* because these tables hold RVA. Try next code:
DWORD* func_table = (DWORD*)(image+pExp_dir->AddressOfFunctions); //Get an array of pointers to the functions
WORD* ord_table = (WORD*)(image+pExp_dir->AddressOfNameOrdinals); //Get an array of ordinals
DWORD* name_table = (DWORD*)(image+pExp_dir->AddressOfNames); //Get an array of function names
for(int i=0;i<pExp_dir->NumberOfNames;i++) //until i is 1 less than how many names there are to iterate through elements
{
printf("%s ", (char*)(image+name_table[i])); //print the name of each function iterated through, I went back and read through these names and didn't see GetProcAddress anywhere
if(strcmp(proc_name, (const char*)(image+name_table[i])) == 0) //Is it the function we're looking for?
{
// TODO should we distinguish between normal and forwarded exports?
WORD ordinal_base = 1; // TODO read it from export directory
address = func_table[ord_table[i] - ordinal_base];//If so convert the address of the function into a DWORD(hexadecimal)
system("pause");
system("CLS"); //Clear the screen
return address; //return the address of the function
}
}
So when your code runs on 32-bit machine it should work regardless of the incorrect var types, but if you are on 64-bit - pointers are twice longer than DWORD and it will skip odd entries in tables and goes out of array bound, that may cause crash.
P.S. Name table is ordered, so you can use binary search.
I have following structure:
typedef struct generic_attribute_struct{
attribute_value current_value;
attribute_value previous_value;
attribute_value running_value;
} generic_attribute;
where attribute_value is simply a placeholder for unsigned long long int.
I have the following constructor for this structure:
generic_attribute* construct_generic_attribute(attribute_value current_value){
generic_attribute *ga_ptr; //allocate space for pointer to generic attribute
if(ga_ptr = malloc (sizeof (generic_attribute))){ //if allocation succeeds
set_ga_current_value(ga_ptr, current_value); //assigned the current value to given input
set_ga_previous_value(ga_ptr, 0); //set previous value to zero
set_ga_running_value(ga_ptr);
} else{ //else, inform user of error
fprintf(stderr, "Health Monitor ran out of space when allocating memory for a generic attribute.");
}
return ga_ptr; // return pointer to new attribute or a NULL pointer if memory allocation failed
}
where set_ga_running_value looks like this:
attribute_value set_ga_running_value(generic_attribute* ga_ptr){
attribute_value delta = get_ga_current_value(ga_ptr) - get_ga_previous_value(ga_ptr);
ga_ptr->running_value = (ga_ptr->running_value? ga_ptr->running_value : 0) + delta;
return ga_ptr->running_value;
}
Destructor for this structure looks like this:
void destroy_generic_attribute(generic_attribute** ga_ptr){
free(*ga_ptr);
}
I created a test that asks the user for some current_value input, constructs a pointer, and prints out whether the values for structure variables are what they ought to be. This test loops until the user no longer wants to test, in which case they quit out of the test.
So, the test looks like this:
Does user want to test? If yes, go to 2). If no, go to 7).
Get input from user
Call constructor for generic attribute with this new input
Verify that generic attribute was created correctly
Call the destructor on generic attribute
Go to 1.
Quit
This is what the test looks like:
void test_generic_attribute_constructor_with_user_input(){
attribute_value input;
int continue_var;
bool current_value_test, previous_value_test, running_value_test, pointer_test;
generic_attribute* ga_ptr;
while(1){
printf("Would you like to execute a test for Generic Attribute Constructor? Type 1 for YES, or 0 for NO: ");
scanf("%i", &continue_var);
if(continue_var){
printf(TESTING, "Constructor for Generic Attribute and Generic Attribute Reader");
printf("\n" INPUT, "single number");
scanf("%lld", &input);
ga_ptr = construct_generic_attribute(input);
read_generic_attribute(ga_ptr);
current_value_test = (get_ga_current_value(ga_ptr) == input ? true : false);
previous_value_test = (get_ga_previous_value(ga_ptr) == 0 ? true: false);
// THIS TEST FAILS
running_value_test = (get_ga_running_value(ga_ptr) == input ? true: false);
pointer_test = (ga_ptr ? true: false);
printf("%s.\n", ((current_value_test && previous_value_test && running_value_test && pointer_test) ? PASS : FAIL));
destroy_generic_attribute(&ga_ptr);
}else{
printf("\nOK! Testing concluded.");
break;
}
}
}
My problem is that the "running value" seems to never get "reset" when the ga_ptr gets destroyed. It seems to keep its old value. How would I clear memory for the entire ga_ptr structure properly?
test result:
Would you like to execute a test for Generic Attribute Constructor? Type 1 for YES, or 0 for NO: 1
Testing Constructor for Generic Attribute and Generic Attribute Reader:
Please enter single number for input: 10
Generic Attribute has the following contents:
Pointer Current Value Previos Value Running Value
0x600058530 10 0 10
PASS.
Would you like to execute a test for Generic Attribute Constructor? Type 1 for YES, or 0 for NO: 1
Testing Constructor for Generic Attribute and Generic Attribute Reader:
Please enter single number for input: 20
Generic Attribute has the following contents:
Pointer Current Value Previos Value Running Value
0x600058530 20 0 30
FAIL.
I would expect the Running value to be 20.
If I change the destructor to this:
void destroy_generic_attribute(generic_attribute** ga_ptr){
set_ga_current_value(*ga_ptr, 0);
set_ga_previous_value(*ga_ptr, 0);
(*ga_ptr)->running_value = 0;
free(*ga_ptr);
}
My test pass... However, I do not understand why skipping the setters makes the code fail.
You are just invoking undefined behaviour by using a never initialized value.
In construct_generic_attribute, you initialize current and previous value and then call set_ga_running_value. In the latter, you use current and previous values that have just been initialize to compute delta : fine until here. But then you have :
ga_ptr->running_value = (ga_ptr->running_value? ga_ptr->running_value : 0) + delta;
Meaning that you use running_value before initializing it. As it is in a freshly malloc'ed struct, its value is just undefined. It might be 0, or it might be the value that existed in this memory location before allocation, or it might be a special value that compiler uses as a special initialization : you cannot know and should not rely on anything.
You compiler seems to preinitialize memory to 0 on run and then never change the value on free and malloc, giving 30 on second run. Mine (in debug mode) allways initialized malloc'ed values to 0xcdcdcdcd, giving FAIL on each test. Just undefined behaviour ...
So you really should initialize the freshed allocated struct in your constructor :
if(ga_ptr = malloc (sizeof (generic_attribute))){ //if allocation succeeds
memset(ga_ptr, 0, sizeof(generic_attribute)); // ensure all values are set to 0
set_ga_current_value(ga_ptr, current_value); //assigned the current value to given input
set_ga_previous_value(ga_ptr, 0); //set previous value to zero
set_ga_running_value(ga_ptr);
or if you know that running_value is an integral, just replace the memset with:
ga_ptr->running_value = 0;
I am writing a program to store multiple typedef "Item" instances in a queue (using this queue implementation) and I am running into a problem getting the data back from the queue.
Here is the relevant code, minus the file open/close lines (the code takes an input file and stores individual values into the instance):
Sample file:
1 2 10 20 30
------------
/* create new item */
Item *newItem = malloc(sizeof(Item));
/* string tokenizer */
...
/* set item variables */
newItem->value1 = strtol(tokens[0], NULL, 10); //should contain 1
newItem->value2 = strtol(tokens[1], NULL, 10); //should contain 2
newItem->value3 = strtol(tokens[2], NULL, 10); //should contain 10
newItem->value4 = strtol(tokens[3], NULL, 10); //should contain 20
newItem->value5 = strtol(tokens[4], NULL, 10); //should contain 30
/* add to item queue */
queue_push_tail(itemQueue, &newItem);
/* add second item with different values, same method as above */
...
/* check queue values */
if(!queue_is_empty(itemQueue)) {
Item *itemHead = queue_peek_head(itemQueue); //this should differ...
printf("Head: %d %d\n", itemHead->value1, itemHead->value5);
Item *itemTail = queue_peek_tail(processQueue); //...from this
printf("Tail: %d %d\n", itemTail->value1, itemTail->value5);
}
How can I then access one of these items to view a variable? I thought I could use something like queue_peek_head(itemQueue)->value1 to see the first variable in the item (in the above example, 1 since that was stored in the first newItem.value1 in the queue), but that doesn't work for some reason.
Like #WhozCraig said in the previous comment, queue_peek_head() is supposed to return 'void *' which you should cast to 'Item *'.
Another issue with your code - 'newItem' is an on-stack variable, you can keep in a queue only as long as you are within the call stack of the function that pushed newItem to the queue. A safer practice would be to allocate newItem before pushing to a queue and free it somewhere else when you don't need it to be queued anymore.
I need to make some operations on a list of files with particular extension (*.bob), all stored in the same directory. The files are image frames, and their name format is frame_XXXX.bob. I don't know the number of frames a priori, and I need to make sure I process them in order (from frame 0 to last one). I read the content of the folder with struct dirent *readdir(DIR *dirp), but since it doesn't guarantee files will be read in alphabetical order (even though it always seems to), I want to put them into a single linked list, and then sort them before processing further.
I save the head of the list before populating it to a pointer filesListStart, then read the entire folder content, adding each entry to the list if it has ".bob" extension. This all works great when I have up to 100 frames, but for some reason breaks down above that - the value of what pointer filesListStart points at doesn't contain the filename of the first entry in the list anymore. The code doesn't use any numerals, so I don't know what would be the significance of going over 100 elements.
I wrote out memory address of filesListStart before I start populating the list, and after, and they are the same, but values they show at magically change. When I set filesListStart it points at object with field fileName equals to "frame_0000.bob" (which is as expected), but after populating the list the name it points at becomes "e_0102.bob".
The list structure is defined as
// List structure
struct FilesList {
char *fileName ;
struct FilesList *next ;
} ;
The code in question is:
DIR *moviesDir ;
moviesDir = opendir("movies") ;
if(moviesDir == NULL)
{
printf("Make Movie failed to open directory containing bob frames\n") ;
return ;
}
struct dirent *dirContent ;
// Get first .bob frame name from the directory
dirContent = readdir(moviesDir) ;
// isBobFile(dirContent) returns 1 if entry has ".bob" extension and 0 otherwise
while( !isBobFile(dirContent) )
{
dirContent = readdir(moviesDir) ;
}
struct FilesList *filesList = (struct FilesList*)
malloc( sizeof(struct FilesList) ) ;
// Initialize the list start at that first found .bob frame
filesList->fileName = dirContent->d_name;
// And save the head of the list
struct FilesList *filesListStart = filesList ;
printf("FilesListStart: %s\n", filesListStart->fileName) ;
printf("Address is: %p\n", filesListStart) ;
// For all other bob frames
while( (dirContent = readdir(moviesDir) ) != NULL )
{
if( isBobFile(dirContent) )
{
struct FilesList *temporaryNode = (struct FilesList*)
malloc( sizeof(struct FilesList) );
temporaryNode->fileName = dirContent->d_name ;
filesList->next = temporaryNode ;
filesList = temporaryNode ;
}
}
// Set the 'next' pointer of the last element in list to NULL
filesList->next = NULL ;
// close stream to directory with .bob frames
closedir(moviesDir) ;
// Check what FilesListStart points at
printf("FilesListStart: %s\n", filesListStart->fileName) ;
printf("Address is: %p\n", filesListStart) ;
// Rest of the code
You should be making a copy of dirContent->d_name rather than using the actual value.
The runtime libraries are free to change the contents of that dirent structure whenever you call readdir and, if all you've stored is it's address, the underlying memory may change. From the POSIX man-pages:
The pointer returned by readdir() points to data which may be overwritten by another call to readdir() on the same directory stream.
In other words, replace the lines:
filesList->fileName = dirContent->d_name;
temporaryNode->fileName = dirContent->d_name ;
with:
filesList->fileName = strdup (dirContent->d_name);
temporaryNode->fileName = strdup (dirContent->d_name);
assuming you have a strdup-like function and, if not, you can get one cheap here.
If it's only changing after 100 calls, it's probably the runtime trying to be a bit more intelligent but even it can't store an infinite number so it probably sets a reasonable limit.
Just remember to free all those char pointers before you free the linked list nodes (somewhere in that "rest of code" section presumably).
I'm making a domino game and when the user adds a domino to the left, the domino is added but when the function exits the domino added is GONE.
FYI:
fitxesJoc (Link List) contains the dominoes of
the game and is a pointer passed to the function (so that it lasts all the game)
opcionesCorrectas (Domino) contains the correct choices of domino
inferior (int) contains the smaller number of the domino
superior (int) contains the bigger number of the domino
pos (int) the position of the domino
opcionFitxa (int) contains the choice of the player
ultimaFitxa->seg is the 'next' node
tNode* ultimaFitxa = (tNode *)malloc(sizeof(tNode));
ultimaFitxa->info.inferior = opcionesCorrectas[opcionFitxa - 1].inferior;
ultimaFitxa->info.superior = opcionesCorrectas[opcionFitxa - 1].superior;
ultimaFitxa->info.pos = opcionesCorrectas[opcionFitxa - 1].pos;
ultimaFitxa->seg = fitxesJoc;
fitxesJoc = ultimaFitxa;
Header of the function
unsigned int demanar_fitxa_tirar(tJugador *jugador, tNode* fitxesJoc, tPartida *partida, tPila* fitxesBarrejades, bool primerCop)
Call of the function
resultado = demanar_fitxa_tirar(&Jugadors[jugadorActual], fitxesJoc, partida, fitxesBarrejades, true);
This way I add the domino, in the top of the other dominoes.
Your problem is that the last line of demanar_fitxa_tirar:
fitxesJoc = ultimaFitxa;
is assigning to a local variable, which has no effect on the calling code. You need to pass a pointer to the calling code's fitxesJoc, like this:
unsigned int demanar_fitxa_tirar(..., tNode** fitxesJoc, ...) // Note extra *
{
// ...
*fitxesJoc = ultimaFitxa; // Note extra *
}
void mainProgram()
{
tNode* fitxesJoc;
// ...
resultado = demanar_fitxa_tirar(..., &fitxesJoc, ...); // Note extra &
// ...
}
From your code, it's not clear where your function starts and ends and what it takes as parameters but I guess your problem is with the fitxesJoc variable which is probably passed as an argument to the function. C copies arguments when calling functions (call-by-value). You could pass the address to fitxesJoc variable using a pointer instead and rewrite it as something like this:
// fitxesJoc would be a `tNode**` rather than `tNode*`.
tNode* ultimaFitxa = (tNode *)malloc(sizeof(tNode));
ultimaFitxa->info.inferior = opcionesCorrectas[opcionFitxa - 1].inferior;
ultimaFitxa->info.superior = opcionesCorrectas[opcionFitxa - 1].superior;
ultimaFitxa->info.pos = opcionesCorrectas[opcionFitxa - 1].pos;
ultimaFitxa->seg = *fitxesJoc;
*fitxesJoc = ultimaFitxa;
I don't think you've provided enough code, but I suspect the problem is in:
fitxesJoc = ultimaFitxa;
(Linked-list now equals the new Node).
The problem is that parameters are passed by value.
If you want to change the value of the parameter, you'll need to pass by pointer,
and use the pointer to change the value.
*pfitxesJoc = ultimaFitxa;
Please provide more code, including the function header and the function call, for a better answer.
It looks like you're not actually adding the new domino to the linked list. But, it's hard to tell because you need to post more code, and because your code isn't in English.