|
I do not understand why is the pointer address changing everytime during the output for a code while I am executing the same code?
The code:
int main()
{
int a;
a=100;
int *b;
b= &a;
printf("The address of a is %p\n", b);
return 0;
}
The gcc compiler output:
nikhil@nikhil-Lenovo-Product:~/Desktop$ ./a.out
The address of a is 0x7fff990d2f24
nikhil@nikhil-Lenovo-Product:~/Desktop$ ./a.out
The address of a is 0x7fffcec94eb4
nikhil@nikhil-Lenovo-Product:~/Desktop$ ./a.out
The address of a is 0x7fff70b595e4
nikhil@nikhil-Lenovo-Product:~/Desktop$
|
|
|
|
|
This is not raleted to C but on how executable programs are loaded into memory. Each time you start the program it is loaded into previously free memory space. The free memory space and possible start adresses are changing because there are also other tasks and programs allocating and freeing memory.
|
|
|
|
|
In addition to what already told you have to consider that the variable whose address you are watching is a local automatic variable that resides on the stack that is is even more variable.
|
|
|
|
|
That is not quite correct, since each process uses its own address space, and memory addresses within a program do not correspond to physical memory addresses. The system memory manager instead creates a virtual memory address space for each process and maps that space onto the actual physical addresses. These addresses may change, specifically when some of that virtual memory exceeds the physical memory available.
Therefore, theoretically, the system memory manager could guarantee to always provide the same memory pointer upon repeated runs of a program. However, the memory manager is written to be efficient, not consistent between runs. I'm not that much into the inner workings of system memory managers, but I suspect that - depending on the current address space mappings - they will try to place allocations in regions of continuous physical memory to minimize the time they need searching. These regions will vary for the reasons you mentioned: other services and programs that are also using (and releasing) memory.
GOTOs are a bit like wire coat hangers: they tend to breed in the darkness, such that where there once were few, eventually there are many, and the program's architecture collapses beneath them. (Fran Poretto)
|
|
|
|
|
Hi Stefan,
Mike Nordell below gave a probable correct answer in that it is most likely due to ASLR. We don't know for sure since the original poster did not include OS version. Many modern operating systems are implementing this now including Linux.
My suggestion for the original poster is to recompile his project with /DYNAMICBASE[^] disabled. If he gets the same result after recompiling with /DYNAMICBASE disabled then he should check if Force ASLR[^] is enabled. (I am assuming he is on Windows and compiling with gcc within Cygwin based on his shell prompt)
Best Wishes,
-David Delaune
|
|
|
|
|
Maybe ASLR is the answer. But I see a lot of open questions. For one, my understanding of ASLR is that it will only randomize the memory address of the code area, and that area is separate from both the stack and the heap areas. Second, even if ASLR does also randomize the physical address of the stack or heap areas, will that have an effect on data addresses within an application? AFAIK it should not! If that were true, how could memory virtualization work? Third, I've seen data addresses both stay the same and change to different values on restarting an application (the same application, without changes to the code), implying that the address modifications are not deliberate.
But as I said, I do not know the internals of the Windows memory manager. Maybe ASLR does have a subtle (possibly unintended) side effect that influences data memory addresses within the application.
Anyway, I see very little use in querying data addresses. They do not directly correspond to physical addresses, they can and will be affected by changes in the code, and they will likely be different on different machines, even if they can be made to stay conatant on the same machine. The only thing I use data addresses for is setting data breakpoints - and I try to avoid those normally since they tend to eat a lot of performance.
P.S.: I've just checked the Wiki Article on ASLR[^] which was a bit more informative than the ones you linked to: apparently, in Windows, the ASLR implementation does randomize stack and heap addresses too. The physical addresses, mind you. That doesn't explain variations of the virtual addresses visible within the application though.
GOTOs are a bit like wire coat hangers: they tend to breed in the darkness, such that where there once were few, eventually there are many, and the program's architecture collapses beneath them. (Fran Poretto)
modified 13-Feb-15 3:21am.
|
|
|
|
|
Most likely ASLR - Address Space Layout Randomization.
The operating system is trying to help you not get pwnd due to easily exploitable crappy code.
|
|
|
|
|
Hi,
You are hitting at a genuine question here. Seeing that you use the GNU Compiler, I take it that you are running Linux. I take it, that you close down each exe, before starting the next instance. Then again, each instance starts in it's own virtual memory space. All your variables are stack based, and it suggests that Linux sets up a Random Stack Base, when a Process is started. This may be caused by the Debugger you use, if the results you display, are a result of Debugging Runs. Try it again in Retail Mode.
Whereas your question is of academic interest, I cannot see any practical implications, or even, Application. Anything that assumes a Fixed Location in Memory of Anything, relating to a running program, is ultimately bad design, and doomed to failure.
Kind Regards
Bram van Kampen
|
|
|
|
|
how do a write a code to switch on the LED using pic16f877A
|
|
|
|
|
|
By configuring the port with your LED as output (writing to the TRIS_x register) and setting the output state to the level which lets current flow through your LED (writing to the PORT_x register; the level depends on how the LED is connected).
|
|
|
|
|
What is that pic16f877A that you're going to use to write the code to turn the LED on?
I believe you're asking a question for some circuit board, if that is the case, then you should know that most of the board manufacturers have an API, and a developer forum that can guide you. You can use thode documents to get help in performing different actions, like the basic on turning the LED on.
The sh*t I complain about
It's like there ain't a cloud in the sky and it's raining out - Eminem
~! Firewall !~
|
|
|
|
|
Hello friends,
I have a HANDLE obtained by CreateFile() function call in windows, Is there any way i can assign that HANDLE to
CComPtr<istream>
|
|
|
|
|
|
Hello,
i'm a newbie in MFC programming and I'm writing a simple and silly program that change the background color of the window by selecting the color in the Menù.
I've created a menù with 5 color and each color has its own ID message.
I put the handler of these messages in the Document class of the program: i don't know if this is correct.
How can I change the color of background? I'm a bit confused because I would like to invalidate the client area and set the new color in OnDraw Method but I can't invalidate the area because if i put Invalidate() in the handler of the menù i get error.
These questions could be silly and obvious for an expert user but I don't know how to proceed. Can anyone suggest me the way to do? Best regards.
|
|
|
|
|
What type of view are you using? What error do you get when you call Invalidate() ?
The difficult we do right away...
...the impossible takes slightly longer.
|
|
|
|
|
If i put
Invalidate();
in the handler I get the message:
"error C3861: 'Invalidate': identifier not found
I have a doubt: Invalidate is a method of Cview class and I call this function inside a method of CDocument class. Is this calling correct? How can I call a method of a class inside a method of another class?
|
|
|
|
|
You should use the UpdateAllViews [^] function of your CDocument derived class. That will then call the correct method for each CView derived object to update itself.
|
|
|
|
|
I am trying to implement a service provider to connect with a hardware device. request some suggestion on my approach and ideas to implement a robust system.
Mentioned are the raised requirements
0. Receive data from other EXE process
1. To process received Q information.
2. Asynchronously send information on some failure.
TO implement the mentioned system:
1. Selected 2 named pipe (commandRecv & commandSend)
2. CommandRecv pipe will be used as "Named Pipe Server Using Overlapped" I/O"
3. commandSend pipe will be used for sending the processed information.
4. commandSend will also need to send all the async messages from service provider to connected application.
On init system will create a thread to hold connection instance of commandSend pipe.After creating thread instance commandRecv pipe will be set to overlapped I/O mode and process recieve queue information.
This is the code which i am trying to extend:
<pre>#include <windows.h>
#include <stdio.h>
#include <tchar.h>
#define CONNECTING_STATE 0
#define READING_STATE 1
#define WRITING_STATE 2
#define INSTANCES 4
#define PIPE_TIMEOUT 5000
#define BUFSIZE 4096
typedef struct
{
OVERLAPPED oOverlap;
HANDLE hPipeInst;
TCHAR chRequest[BUFSIZE];
DWORD cbRead;
TCHAR chReply[BUFSIZE];
DWORD cbToWrite;
DWORD dwState;
BOOL fPendingIO;
int processId;
} PIPEINST, *LPPIPEINST;
typedef struct
{
char appName[256];
int processId;
}PIPEHANDSHAKE;
VOID DisconnectAndReconnect(DWORD);
BOOL ConnectToNewClient(HANDLE, LPOVERLAPPED);
VOID GetAnswerToRequest(LPPIPEINST);
PIPEINST Pipe[INSTANCES];
HANDLE hEvents[INSTANCES];
HANDLE responsePipeHandle[INSTANCES];
DWORD WINAPI InstanceThread(LPVOID);
HANDLE hPipeHandles[10];
PULONG s;
LPTSTR lpszPipename = TEXT("\\\\.\\pipe\\mynamedpipe");
LPTSTR lpszResponsePipe = TEXT("\\\\.\\pipe\\mynamedpipe1");
int responsePipeConnectionHandler(VOID)
{
BOOL fConnected = FALSE;
DWORD dwThreadId = 0;
HANDLE hPipe = INVALID_HANDLE_VALUE, hThread = NULL;
int cbBytesRead;
INT threadCount=0;
char bufferSize[512];
for (;;)
{
_tprintf( TEXT("\nPipe Server: Main thread awaiting client connection on %s\n"), lpszResponsePipe);
hPipe = CreateNamedPipe(
lpszResponsePipe,
PIPE_ACCESS_DUPLEX,
PIPE_TYPE_MESSAGE |
PIPE_READMODE_MESSAGE |
PIPE_WAIT,
PIPE_UNLIMITED_INSTANCES,
BUFSIZE,
BUFSIZE,
0,
NULL);
if (hPipe == INVALID_HANDLE_VALUE)
{
_tprintf(TEXT("CreateNamedPipe failed, GLE=%d.\n"), GetLastError());
return -1;
}
fConnected = ConnectNamedPipe(hPipe, NULL) ?
TRUE : (GetLastError() == ERROR_PIPE_CONNECTED);
if(fConnected){
PIPEHANDSHAKE processData;
fConnected = ReadFile(
hPipe,
bufferSize,
sizeof(PIPEHANDSHAKE),
&cbBytesRead,
NULL);
memset(&processData,0,sizeof(PIPEHANDSHAKE));
memcpy(&processData,&bufferSize,sizeof(PIPEHANDSHAKE));
printf("APP Process id: %d , app name: %s",processData.processId,processData.appName);
}
}
return 0;
}
DWORD WINAPI InstanceThread(LPVOID lpvParam)
{
HANDLE hHeap = GetProcessHeap();
TCHAR* pchRequest = (TCHAR*)HeapAlloc(hHeap, 0, BUFSIZE*sizeof(TCHAR));
TCHAR* pchReply = (TCHAR*)HeapAlloc(hHeap, 0, BUFSIZE*sizeof(TCHAR));
DWORD cbBytesRead = 0, cbReplyBytes = 0, cbWritten = 0;
BOOL fSuccess = FALSE;
HANDLE hPipe = NULL;
if (lpvParam == NULL)
{
printf( "\nERROR - Pipe Server Failure:\n");
printf( " InstanceThread got an unexpected NULL value in lpvParam.\n");
printf( " InstanceThread exitting.\n");
if (pchReply != NULL) HeapFree(hHeap, 0, pchReply);
if (pchRequest != NULL) HeapFree(hHeap, 0, pchRequest);
return (DWORD)-1;
}
if (pchRequest == NULL)
{
printf( "\nERROR - Pipe Server Failure:\n");
printf( " InstanceThread got an unexpected NULL heap allocation.\n");
printf( " InstanceThread exitting.\n");
if (pchReply != NULL) HeapFree(hHeap, 0, pchReply);
return (DWORD)-1;
}
if (pchReply == NULL)
{
printf( "\nERROR - Pipe Server Failure:\n");
printf( " InstanceThread got an unexpected NULL heap allocation.\n");
printf( " InstanceThread exitting.\n");
if (pchRequest != NULL) HeapFree(hHeap, 0, pchRequest);
return (DWORD)-1;
}
printf("InstanceThread created, receiving and processing messages.\n");
hPipe = (HANDLE) lpvParam;
while (1)
{
fSuccess = ReadFile(
hPipe,
pchRequest,
BUFSIZE*sizeof(TCHAR),
&cbBytesRead,
NULL);
if (!fSuccess || cbBytesRead == 0)
{
if (GetLastError() == ERROR_BROKEN_PIPE)
{
_tprintf(TEXT("InstanceThread: client disconnected.\n"), GetLastError());
}
else
{
_tprintf(TEXT("InstanceThread ReadFile failed, GLE=%d.\n"), GetLastError());
}
break;
}
else{
printf(" Recieved data in PIPE");
}
cbReplyBytes = (strlen(pchRequest)+1)*sizeof(TCHAR);
fSuccess = WriteFile(
hPipe,
pchRequest,
cbReplyBytes,
&cbWritten,
NULL);
if (!fSuccess || cbReplyBytes != cbWritten)
{
_tprintf(TEXT("InstanceThread WriteFile failed, GLE=%d.\n"), GetLastError());
break;
}
}
FlushFileBuffers(hPipe);
DisconnectNamedPipe(hPipe);
CloseHandle(hPipe);
HeapFree(hHeap, 0, pchRequest);
HeapFree(hHeap, 0, pchReply);
printf("InstanceThread exitting.\n");
return 1;
}
int _tmain(VOID)
{
DWORD i, dwWait, cbRet, dwErr,hThread;
BOOL fSuccess;
int dwThreadId;
hThread = CreateThread(
NULL,
0,
responsePipeConnectionHandler,
NULL,
0,
&dwThreadId);
if (hThread == NULL)
{
printf("Response server creation failed with %d.\n", GetLastError());
return 0;
}
for (i = 0; i < INSTANCES; i++)
{
hEvents[i] = CreateEvent(
NULL,
TRUE,
TRUE,
NULL);
if (hEvents[i] == NULL)
{
printf("CreateEvent failed with %d.\n", GetLastError());
return 0;
}
Pipe[i].oOverlap.hEvent = hEvents[i];
Pipe[i].hPipeInst = CreateNamedPipe(
lpszPipename,
PIPE_ACCESS_DUPLEX |
FILE_FLAG_OVERLAPPED,
PIPE_TYPE_MESSAGE |
PIPE_READMODE_MESSAGE |
PIPE_WAIT,
INSTANCES,
BUFSIZE*sizeof(TCHAR),
BUFSIZE*sizeof(TCHAR),
PIPE_TIMEOUT,
NULL);
if (Pipe[i].hPipeInst == INVALID_HANDLE_VALUE)
{
printf("CreateNamedPipe failed with %d.\n", GetLastError());
return 0;
}
Pipe[i].fPendingIO = ConnectToNewClient(
Pipe[i].hPipeInst,
&Pipe[i].oOverlap);
Pipe[i].dwState = Pipe[i].fPendingIO ?
CONNECTING_STATE :
READING_STATE;
}
while (1)
{
dwWait = WaitForMultipleObjects(
INSTANCES,
hEvents,
FALSE,
INFINITE);
i = dwWait - WAIT_OBJECT_0;
if (i < 0 || i > (INSTANCES - 1))
{
printf("Index out of range.\n");
return 0;
}
if (Pipe[i].fPendingIO)
{
fSuccess = GetOverlappedResult(
Pipe[i].hPipeInst,
&Pipe[i].oOverlap,
&cbRet,
FALSE);
switch (Pipe[i].dwState)
{
case CONNECTING_STATE:
if (! fSuccess)
{
printf("Error %d.\n", GetLastError());
return 0;
}
Pipe[i].dwState = READING_STATE;
break;
case READING_STATE:
if (! fSuccess || cbRet == 0)
{
DisconnectAndReconnect(i);
continue;
}
Pipe[i].cbRead = cbRet;
Pipe[i].dwState = WRITING_STATE;
break;
case WRITING_STATE:
if (! fSuccess || cbRet != Pipe[i].cbToWrite)
{
DisconnectAndReconnect(i);
continue;
}
Pipe[i].dwState = READING_STATE;
break;
default:
{
printf("Invalid pipe state.\n");
return 0;
}
}
}
switch (Pipe[i].dwState)
{
case READING_STATE:
fSuccess = ReadFile(
Pipe[i].hPipeInst,
Pipe[i].chRequest,
BUFSIZE*sizeof(TCHAR),
&Pipe[i].cbRead,
&Pipe[i].oOverlap);
if (fSuccess && Pipe[i].cbRead != 0)
{
Pipe[i].fPendingIO = FALSE;
Pipe[i].dwState = WRITING_STATE;
continue;
}
dwErr = GetLastError();
if (! fSuccess && (dwErr == ERROR_IO_PENDING))
{
Pipe[i].fPendingIO = TRUE;
continue;
}
DisconnectAndReconnect(i);
break;
case WRITING_STATE:
GetAnswerToRequest(&Pipe[i]);
fSuccess = WriteFile(
Pipe[i].hPipeInst,
Pipe[i].chReply,
Pipe[i].cbToWrite,
&cbRet,
&Pipe[i].oOverlap);
if (fSuccess && cbRet == Pipe[i].cbToWrite)
{
Pipe[i].fPendingIO = FALSE;
Pipe[i].dwState = READING_STATE;
continue;
}
dwErr = GetLastError();
if (! fSuccess && (dwErr == ERROR_IO_PENDING))
{
Pipe[i].fPendingIO = TRUE;
continue;
}
DisconnectAndReconnect(i);
break;
default:
{
printf("Invalid pipe state.\n");
return 0;
}
}
}
return 0;
}
VOID DisconnectAndReconnect(DWORD i)
{
if (! DisconnectNamedPipe(Pipe[i].hPipeInst) )
{
printf("DisconnectNamedPipe failed with %d.\n", GetLastError());
}
Pipe[i].fPendingIO = ConnectToNewClient(
Pipe[i].hPipeInst,
&Pipe[i].oOverlap);
Pipe[i].dwState = Pipe[i].fPendingIO ?
CONNECTING_STATE :
READING_STATE;
}
BOOL ConnectToNewClient(HANDLE hPipe, LPOVERLAPPED lpo)
{
BOOL fConnected, fPendingIO = FALSE;
fConnected = ConnectNamedPipe(hPipe, lpo);
if (fConnected)
{
printf("ConnectNamedPipe failed with %d.\n", GetLastError());
return 0;
}
switch (GetLastError())
{
case ERROR_IO_PENDING:
fPendingIO = TRUE;
break;
case ERROR_PIPE_CONNECTED:
if (SetEvent(lpo->hEvent))
break;
default:
{
printf("ConnectNamedPipe failed with %d.\n", GetLastError());
return 0;
}
}
return fPendingIO;
}
VOID GetAnswerToRequest(LPPIPEINST pipe)
{
_tprintf( TEXT("[%d] %s\n"), pipe->hPipeInst, pipe->chRequest);
strncpy(pipe->chReply, "Default answer from server",BUFSIZE);
pipe->cbToWrite = (lstrlen(pipe->chReply)+1)*sizeof(TCHAR);
}</pre>
Current pending activities:
1. Need to get process id of the connected process. this will be mainly used for identifying the client to send response data.
Since the system is developed under MINGW - WIN32 - server will not be able to get the process id directly by using (GetNamedPipeClientProcessId). need to form a message structure on getting a client connection.
|
|
|
|
|
Why you can't use GetNamedPipeClientProcessId()?
Your limit is not MingW-32, but your OS.
This function isn't available on XP and below.
If you're developing on VISTA and above be shure that the WINVER and _WIN32_WINNT are correctly set for VISTA or above see here.
If you're developing on XP you're no luky, there is no way other than access file informations in kernel mode (you have to write a driver to do that).
modified 9-Feb-15 9:57am.
|
|
|
|
|
Yup, you are tight , iwas jsut able to extend and use it directly...
|
|
|
|
|
How I can read and write dicom image via c++?
|
|
|
|
|
Maybe this[^] link will help.
"the debugger doesn't tell me anything because this code compiles just fine" - random QA comment
"Facebook is where you tell lies to your friends. Twitter is where you tell the truth to strangers." - chriselst
|
|
|
|
|
I wrote a program which includes these declarations:-
class PEN{public: HDC d; HPEN pen,old;
PEN(HDC dc,COLORREF col);
~PEN();};
/*-----*/
/* the device context dc must still exist when the pen is deleted */
PEN::PEN(HDC dc,COLORREF col){ d=dc;
pen=(HPEN)CreatePen(0,1,col);
old=(HPEN)SelectObject(dc,pen);};
PEN::~PEN(){ SelectObject(d,old);
DeleteObject(pen);};
/*-----*/
// then I can write for example:-
/*-----*/
if(xhairs) {
PEN orange(WIdc,RGB(255,128,0)); Line(WIdc,0,b/2,(int)(2*a),(int)(b/2));
Line(WIdc,(int)(a/2),0,(int)(a/2),b);
Line(WIdc,(int)(a*1.5),0,(int)(a*1.5),b);}
/*-----*/
and the new pen is automatically cleared away when control leaves the block where the pen was declared.
And similarly with fonts etc.
modified 3-Feb-15 9:41am.
|
|
|
|
|
And your question is?
The difficult we do right away...
...the impossible takes slightly longer.
|
|
|
|
|