DFH: Sizeof(Object) giving weird output with fin.seekg(); - file-handling

Here is the function:
void debugged_read()
{
clrscr();
stu S1;
ifstream fin;
eof=false;
fin.open("CP2.dat", ios::binary); //Opens the file again
while(fin.eof() == false) {
cout<<"\n\n Initial location: "<<fin.tellg();
fin.read((char*)& S1, sizeof(S1)); //Reads a Record into fin stream
S1.show();
cout<<"\n\n After Read location: "<<fin.tellg();
fin.read((char*)& S1, sizeof(S1)); //Reads the next record space for eof detection
cout<<"\n Check position: "<<fin.tellg();
if(fin.eof() == true) {
cprintf("\nWARNING: End of file Incoming!");
break; //Break on eof encounter
}
else {
fin.seekg(-(sizeof(S1)), ios :: cur); //File Pointer Correction
cout<<"\n File Pointer Corrected: "<<fin.tellg();
}
}
cout<<"\nRead Successful!";
fin.close();
}
This function returned an expected output if I used a long variable to store the size of the object S1 of 'stu' class.
but using the sizeof(); directly it gives this weird output:

sizeof returns size_t which is unsigned int
istream::read expects streamsize which is signed int

Related

CS50 pset5 Speller [2022] - " :( program is free of memory errors"

I get error ":( program is free of memory errors valgrind tests failed; see log for more information."
Here is my code:
// Implements a dictionary's functionality
#include <ctype.h>
#include <stdbool.h>
#include <string.h>
#include <strings.h>
#include <stdlib.h>
#include <stdio.h>
#include "dictionary.h"
// Represents a node in a hash table
typedef struct node
{
char word[LENGTH + 1];
struct node *next;
}
node;
// TODO: Choose number of buckets in hash table
const unsigned int N = 26;
// Hash table
node *table[N];
//Declare variables
unsigned int word_count;
unsigned int hash_value;
// Returns true if word is in dictionary, else false
bool check(const char *word)
{
// TODO
hash_value = hash(word);
node *cursor = table[hash_value];
// Go in link list
while (cursor != 0)
{
if (strcasecmp(word, cursor->word) == 0)
{
return true;
}
cursor = cursor->next;
}
return false;
}
// Hashes word to a number
unsigned int hash(const char *word)
{
// TODO: Improve this hash function
unsigned long total = 0;
for (int i = 0; i < strlen(word); i++)
{
total += tolower(word[i]);
}
return total % N;
}
// Loads dictionary into memory, returning true if successful, else false
bool load(const char *dictionary)
{
// Open dictionary
FILE *file = fopen(dictionary, "r");
// it would be null if cant be open
if (file == NULL)
{
printf("Unable to open %s\n", dictionary);
return false;
}
// Declare variable words
char word[LENGTH + 1];
//Scan dictionary for strings up until EOF
while (fscanf(file, "%s", word) != EOF)
{
node *n = malloc(sizeof(node));
if (n == NULL)
{
return false;
}
//copy wordds into node
strcpy(n->word, word);
hash_value = hash(word);
n->next = table[hash_value];
table[hash_value] = n;
word_count++;
}
fclose(file);
return true;
}
// Returns number of words in dictionary if loaded, else 0 if not yet loaded
unsigned int size(void)
{
if (word_count > 0)
{
return word_count;
}
return 0;
}
// Unloads dictionary from memory, returning true if successful, else false
bool unload(void)
{
for (int i = 0; i < N; i++)
{
node *cursor = table[i];
while (cursor)
{
node *tmp = cursor;
cursor = cursor->next;
free(tmp);
}
if (cursor == NULL)
{
return true;
}
}
return false;
}
Here are the errors in valgrind check50:
program is free of memory errors valgrind tests failed; see log for more information.
Here is ERR log:
56 bytes in 1 blocks are still reachable in loss record 1 of 1: (file: dictionary.c, line: 80)
And 80th line code is:
while (fscanf(file, "%s", word) != EOF)
{
node *n = malloc(sizeof(node));
if (n == NULL)
{
return false;
}
unload will free one index and return to speller because of this if (cursor == NULL) block. The last node in an index should set cursor to NULL, so function is done. That conditional should be eliminated. There is really no condition in unload that should return false.

How to get memory rd/wr trace for a specific function call using PIN tools

I am trying to dump mem rd/wr trace for a specific function call from my application and after researching a bit I came across a solution to do so.
But since I am very new to PIN usage, I am not sure how to pass routine names (refer to Routine(RTN rtn, VOID *v)) from application to pin tools so that the right callback function gets trigerred. Can someone please help?
As of now If I run the given pin tools, my trace.out is empty because "!isROI" is always set to false.
#include <stdio.h>
#include "pin.H"
#include <string>
const CHAR * ROI_BEGIN = "__parsec_roi_begin";
const CHAR * ROI_END = "__parsec_roi_end";
FILE * trace;
bool isROI = false;
// Print a memory read record
VOID RecordMemRead(VOID * ip, VOID * addr, CHAR * rtn)
{
// Return if not in ROI
if(!isROI)
{
return;
}
// Log memory access in CSV
fprintf(trace,"%p,R,%p,%s\n", ip, addr, rtn);
}
// Print a memory write record
VOID RecordMemWrite(VOID * ip, VOID * addr, CHAR * rtn)
{
// Return if not in ROI
if(!isROI)
{
return;
}
// Log memory access in CSV
fprintf(trace,"%p,W,%p,%s\n", ip, addr, rtn);
}
// Set ROI flag
VOID StartROI()
{
isROI = true;
}
// Set ROI flag
VOID StopROI()
{
isROI = false;
}
// Is called for every instruction and instruments reads and writes
VOID Instruction(INS ins, VOID *v)
{
// Instruments memory accesses using a predicated call, i.e.
// the instrumentation is called iff the instruction will actually be executed.
//
// On the IA-32 and Intel(R) 64 architectures conditional moves and REP
// prefixed instructions appear as predicated instructions in Pin.
UINT32 memOperands = INS_MemoryOperandCount(ins);
// Iterate over each memory operand of the instruction.
for (UINT32 memOp = 0; memOp < memOperands; memOp++)
{
// Get routine name if valid
const CHAR * name = "invalid";
if(RTN_Valid(INS_Rtn(ins)))
{
name = RTN_Name(INS_Rtn(ins)).c_str();
}
if (INS_MemoryOperandIsRead(ins, memOp))
{
INS_InsertPredicatedCall(
ins, IPOINT_BEFORE, (AFUNPTR)RecordMemRead,
IARG_INST_PTR,
IARG_MEMORYOP_EA, memOp,
IARG_ADDRINT, name,
IARG_END);
}
// Note that in some architectures a single memory operand can be
// both read and written (for instance incl (%eax) on IA-32)
// In that case we instrument it once for read and once for write.
if (INS_MemoryOperandIsWritten(ins, memOp))
{
INS_InsertPredicatedCall(
ins, IPOINT_BEFORE, (AFUNPTR)RecordMemWrite,
IARG_INST_PTR,
IARG_MEMORYOP_EA, memOp,
IARG_ADDRINT, name,
IARG_END);
}
}
}
// Pin calls this function every time a new rtn is executed
VOID Routine(RTN rtn, VOID *v)
{
// Get routine name
const CHAR * name = RTN_Name(rtn).c_str();
if(strcmp(name,ROI_BEGIN) == 0) {
// Start tracing after ROI begin exec
RTN_Open(rtn);
RTN_InsertCall(rtn, IPOINT_AFTER, (AFUNPTR)StartROI, IARG_END);
RTN_Close(rtn);
} else if (strcmp(name,ROI_END) == 0) {
// Stop tracing before ROI end exec
RTN_Open(rtn);
RTN_InsertCall(rtn, IPOINT_BEFORE, (AFUNPTR)StopROI, IARG_END);
RTN_Close(rtn);
}
}
// Pin calls this function at the end
VOID Fini(INT32 code, VOID *v)
{
fclose(trace);
}
/* ===================================================================== */
/* Print Help Message */
/* ===================================================================== */
INT32 Usage()
{
PIN_ERROR( "This Pintool prints a trace of memory addresses\n"
+ KNOB_BASE::StringKnobSummary() + "\n");
return -1;
}
/* ===================================================================== */
/* Main */
/* ===================================================================== */
int main(int argc, char *argv[])
{
// Initialize symbol table code, needed for rtn instrumentation
PIN_InitSymbols();
// Usage
if (PIN_Init(argc, argv)) return Usage();
// Open trace file and write header
trace = fopen("roitrace.csv", "w");
fprintf(trace,"pc,rw,addr,rtn\n");
// Add instrument functions
RTN_AddInstrumentFunction(Routine, 0);
INS_AddInstrumentFunction(Instruction, 0);
PIN_AddFiniFunction(Fini, 0);
// Never returns
PIN_StartProgram();
return 0;
}

getc() skips first value of text file (C)

I am trying to read a text file separated by semicolons such as
3;7;9;
4;7;23;
However, every time I call
while ((c = getc(fp))!= EOF)
putchar(c);
it skips the first value (3) and only outputs:
;7;9;
4;7;23;
Is there any way to get the first value?
Thank you
using C Program.*/
include
int main(){
//file nane
const char *fileName="sample.txt";
//file pointer
FILE *fp;
//to store read character
char ch;
//open file in read mode
fp=fopen(fileName,"r");
if(fp==NULL){
printf("Error in opening file.\n");
return -1;
}
printf("Content of file\n");
while((ch=getc(fp))!=EOF){
printf("%c",ch);
}
fclose(fp);
return 0;
}

Using winsock2, comparing two characters that seem to be equal comes out not equal

Hello fine community at stackoverflow! I've been lurking around using the site for about a year now, and just have come to the need to post a question.
I'm a bit of a klutz when it comes to coding, so go easy on me.
Here's the code (most of it is the sample winsock MSDN code :P):
Client:
#define WIN32_LEAN_AND_MEAN
#include <windows.h>
#include <winsock2.h>
#include <ws2tcpip.h>
#include <stdlib.h>
#include <stdio.h>
#include <iostream>
// Need to link with Ws2_32.lib, Mswsock.lib, and Advapi32.lib
#pragma comment (lib, "Ws2_32.lib")
#pragma comment (lib, "Mswsock.lib")
#pragma comment (lib, "AdvApi32.lib")
void clarify(char *recvdata);
char mdata[7];
#define DEFAULT_BUFLEN 512
#define DEFAULT_PORT "10150"
int main(int argc, char **argv)
{
WSADATA wsaData;
SOCKET ConnectSocket = INVALID_SOCKET;
struct addrinfo *result = NULL,
*ptr = NULL,
hints;
char recvbuf[DEFAULT_BUFLEN];
int iResult;
int recvbuflen = DEFAULT_BUFLEN;
// Initialize Winsock
iResult = WSAStartup(MAKEWORD(2,2), &wsaData);
if (iResult != 0) {
printf("WSAStartup failed with error: %d\n", iResult);
return 1;
}
ZeroMemory( &hints, sizeof(hints) );
hints.ai_family = AF_UNSPEC;
hints.ai_socktype = SOCK_STREAM;
hints.ai_protocol = IPPROTO_TCP;
// Resolve the server address and port
iResult = getaddrinfo("173.21.56.58", DEFAULT_PORT, &hints, &result);
if ( iResult != 0 ) {
printf("getaddrinfo failed with error: %d\n", iResult);
WSACleanup();
return 1;
}
// Attempt to connect to an address until one succeeds
for(ptr=result; ptr != NULL ;ptr=ptr->ai_next) {
// Create a SOCKET for connecting to server
ConnectSocket = socket(ptr->ai_family, ptr->ai_socktype,
ptr->ai_protocol);
if (ConnectSocket == INVALID_SOCKET) {
printf("socket failed with error: %ld\n", WSAGetLastError());
WSACleanup();
return 1;
}
// Connect to server.
iResult = connect( ConnectSocket, ptr->ai_addr, (int)ptr->ai_addrlen);
if (iResult == SOCKET_ERROR) {
closesocket(ConnectSocket);
ConnectSocket = INVALID_SOCKET;
continue;
}
break;
}
freeaddrinfo(result);
if (ConnectSocket == INVALID_SOCKET) {
printf("Unable to connect to server!\n");
WSACleanup();
return 1;
}
// Send an initial buffer
char sendbuf[512];
std::cin.getline(sendbuf, 512);
iResult = send( ConnectSocket, sendbuf, 512, 0 );
if (iResult == SOCKET_ERROR) {
printf("send failed with error: %d\n", WSAGetLastError());
closesocket(ConnectSocket);
WSACleanup();
return 1;
}
std::cout<<"sendbuf: "<<sendbuf<<"\n";
std::cout<<"strlen(sendbuf): "<<strlen(sendbuf)<<"\n";
printf("Bytes Sent: %ld\n", iResult);
// Receive until the peer closes the connection
do {
iResult = recv(ConnectSocket, recvbuf, recvbuflen, 0);
if ( iResult > 0 )
printf("Bytes received: %d\n", iResult);
else if ( iResult == 0 )
printf("Connection closed\n");
else
printf("recv failed with error: %d\n", WSAGetLastError());
std::cout<<"recvbuf: "<<recvbuf<<"\n";
std::cout<<"recvbuflen: "<<recvbuflen<<"\n";
std::cout<<"strlen(recvbuf): "<<strlen(recvbuf)<<"\n";
std::cout<<recvbuf[0]<<"\n";
std::cout<<recvbuf[1]<<"\n";
std::cout<<recvbuf[2]<<"\n";
std::cout<<recvbuf[3]<<"\n";
std::cout<<recvbuf[4]<<"\n";
std::cout<<recvbuf[5]<<"\n";
std::cout<<recvbuf[6]<<"\n";
std::cout<<recvbuf[7]<<"\n";
std::cout<<recvbuf[8]<<"\n";
std::cout<<recvbuf[9]<<"\n";
std::cout<<recvbuf[10]<<"\n";
std::cout<<recvbuf[11]<<"\n";
std::cout<<recvbuf[12]<<"\n";
clarify(recvbuf);
std::cout<<"mdata(main()): "<<mdata<<"\n";
if (mdata == "anarchy") {std::cout<<"This is Anarchy. :)";}
else {std::cout<<"Nope. :( ";}
} while( iResult > 0 );
std::cin.ignore();
// shutdown the connection since no more data will be sent
iResult = shutdown(ConnectSocket, SD_SEND);
if (iResult == SOCKET_ERROR) {
printf("shutdown failed with error: %d\n", WSAGetLastError());
closesocket(ConnectSocket);
WSACleanup();
return 1;
}
// cleanup
closesocket(ConnectSocket);
WSACleanup();
return 0;
}
void clarify(char *recvdata)
{
std::cout<<"recvdata: "<<recvdata<<"\n";
for (int i=0; i<(strlen(recvdata)); i++) {
mdata[i]=recvdata[i];
std::cout<<mdata[i]<<"\n";
}
std::cout<<"mdata(clarify()): "<<mdata<<"\n";
}
And the server code is the sample MSDN winsock code.
I realize the code has a bunch of sloppy extras added in, but rest assured, those are for my own thoughts and reminders. So, please don't bother telling me other places I could clean up. I'll take care of that when I get closer to finishing my project (a long way away :) ).
So, I'm having issues comparing the "mdata" variable with the characters "anarchy".
Even when I send "anarchy" through winsock, it comes back as "anarchy", and I run it through "clarify()" just for good measure, it still doesn't seem to equal "anarchy".
I'm sure it's a noob mistake I'm making here, so please go easy on me...
EDIT:
Here's the output after typing "anarchy" for the "sendbuf" input:
anarchy
sendbuf: anarchy
strlen(sendbuf): 7
bytes sent: 512
bytes recieved: 512
recvbuf: anarchy
recvbuflen: 512
strlen(recvbuf): 7
a
n
a
r
c
h
y
f
4
i
w
,
recvdata: anarchy
a
n
a
r
c
h
y
mdata(clarify()): anarchy
mdata(main()): anarchy
Nope :(
You're comparing the address of a c-string literal to the address stored in mdata.
if (mdata == "anarchy") {std::cout<<"This is Anarchy. :)";}
"anarchy" is a string literal, and has an address. You're comparing that arbitrary address with the address stored in the mdata variable. They're not the same addresses, so the equality check fails.
You don't mean to compare the addresses of where your two strings are stored, you mean to compare the characters stored at those strings.
strncmp is your friend here.

madvise() function not working

I am trying madvise() to mark allocated memory as mergeable so that two applications having same pages can be merged.
While using the madvise() function it shows "invalid argument".
#include<stdio.h>
#include<sys/mman.h>
#include<stdlib.h>
#include<errno.h>
#define ADDR 0xf900f000
int main()
{
int *var1=NULL,*var2=NULL;
size_t size=0;
size = 1000*sizeof(int);
var1 = (int*)malloc(size);
var2 = (int *)malloc(size);
int i=0;
for(i=0;i<999;i++)
{
var1[i] = 1;
}
for(i=0;i<999;i++)
{
var2[i] = 1;
}
i = -1;
while(i<0)
{
i = madvise((void *)var1, size, MADV_MERGEABLE); //to declare mergeable
printf("%d %p\n", i, var1); //to print the output value
err(1,NULL); //to print the generated error
i = madvise((void *)var2, size, MADV_MERGEABLE); //to declare mergeable
printf("%d\n", i);
}
return 0;
}
Error:
a.out: Invalid argument
Please help me.
Thank You.
You can only merge whole pages. You can't merge arbitrary chunks of data.

Resources