Getting segmentation fault while trying to print content member using pointer l_pContent in below program.
#include <iostream>
#include <string.h>
using namespace std;
struct responseStruct {
int Handle;
int headerLen;
int bodyLen;
unsigned char* content;
};
int main()
{
unsigned char l_httpResponse[] = {1,2,3,4,5,6,7,8,9,0,1,2,'a','b','c','d','e','f','g','h','i','j','k','l','a','b','c','d','e','f','g','h','i','j','k','l',0};
struct responseStruct *l_pContent = (struct responseStruct*)l_httpResponse;
cout << l_pContent->content << endl; // Error : Segmentation Fault
return 0;
}
The variable content is a pointer to an unsigned char and so is l_httpResponse. You can therefore create an instance of the responseStruct and then assign the instance's content pointer to l_httpResponse.
Here is an example:
#include <iostream>
#include <string.h>
using namespace std;
struct responseStruct {
int Handle;
int headerLen;
int bodyLen;
unsigned char* content;
};
int main()
{
unsigned char l_httpResponse[] = {1,2,3,4,5,6,7,8,9,0,1,2,'a','b','c','d','e','f','g','h','i','j','k','l','a','b','c','d','e','f','g','h','i','j','k','l',0};
// Create instance of an responseStruct struct
responseStruct rs;
// Make content point to the start of l_httpResponse
rs.content = l_httpResponse;
// Test for access without segfault
cout << static_cast<unsigned>(rs.content[1]) << endl;
return 0;
}
Or here is a live demo.
Omitting the fact that the idea of such code is mysterious to me, here is what causes the error:
If we assume that members of the responseStruct will match ideally the data from the l_httpResponse, that sizeof(int) and sizeof(unsigned char *) are 4, that your architecture uses little-endian notation, and that your compiler uses ASCII (which it probably does), you end with:
Handle == 0x04030201
headerLen == 0x08070605
bodyLen == 0x02010009
content == 0x64636261
Now, content is a pointer, so 0x64636261 is an address in your memory. It doesn't point to your "abcde..." string. It's made up of it's first four bytes. And points at some non existing region. That's why you end up with segmentation fault.
Related
When I am adding
local_w_p_n->wp_val_p = rx_pbuf;
local_w_p_n->wp_val_n = rx_netif;
in rx_local_p_n function to the program code, the code is compiled but running in Process Exit: value 3221225477. Does anyone know why and how to fix it?
#include <iostream>
#include <stdlib.h>
#include <stdio.h>
#include <stdint.h>
struct pbuf{
int a;
int b;
};
struct netif{
int c;
int d;
};
struct wrapper_p_n{ // wrapper for pbuf- and netif-struct pointer
struct pbuf *wp_val_p;
struct netif *wp_val_n;
};
void rx_local_p_n(struct pbuf *rx_pbuf, struct netif *rx_netif)
{
// wrap the received pointer
struct wrapper_p_n *local_w_p_n;
local_w_p_n->wp_val_p = rx_pbuf;
local_w_p_n->wp_val_n = rx_netif;
printf("rx_local_p_n\n");
//Passing *local_w_p_n pointer to another function
//check_value(local_w_p_n);
}
int main(int argc, char** argv) {
// give values to local_pbuf and netif
struct pbuf local_pbuf;
local_pbuf.a = 1;
local_pbuf.b = 2;
struct netif local_netif;
local_netif.c = 3;
local_netif.d = 4;
//passing pbuf- and netif-stuct to function
rx_local_p_n(&local_pbuf, &local_netif);
printf("return\n");
return 0;
}
struct wrapper_p_n *local_w_p_n;
local_w_p_n->wp_val_p = rx_pbuf;
local_w_p_n->wp_val_n = rx_netif;
local_w_p_n is an uninitalised pointer, and dereferencing it is liable to cause your program to crash.
Judging by the commented out code, what you are really looking for is this
struct wrapper_p_n local_w_p_n;
local_w_p_n.wp_val_p = rx_pbuf;
local_w_p_n.wp_val_n = rx_netif;
//Passing pointer to local_w_p_n to another function
check_value(&local_w_p_n);
Instead of declaring a pointer, the code above declares a regular variable, and then uses the address-of operator & to obtain a pointer to that variable.
In fact you wrote exactly the same code in main, so not sure why you tried something different here.
I'm new to C++, and I'm writing a simple blockchain program as a sort of exercise. When I run the below code, I seem to get an error of sorts:
Process returned -1073741819 (0xC0000005)
The code is below:
#include <iostream>
#include <time.h>
#include <string>
using namespace std;
class Block
{
int data, previous_hash;
public:
string timestamp;
Block(string a, int b, int c)
{
timestamp = a;
data = b;
previous_hash = c;
};
};
string getTime()
{
time_t now = time(NULL);
struct tm tstruct;
char buf[40];
tstruct = *localtime(&now);
strftime(buf, sizeof(buf), "%X", &tstruct);
return buf; //Simple code to return current time
}
class BlockChain
{
public:
Block chain[];
BlockChain()
{
chain[0]=createGenesisBlock();
}
Block createGenesisBlock()
{
return Block(getTime(), 10, 0);
}
};
int main()
{
BlockChain myChain;
cout << "current time is " << getTime();
cout << myChain.chain[0].timestamp; //Is this correct?
}
I included a line in main() to access the string timestamp in my object mychain. I suspect this may be the problem, but i'm not sure how else I can access timestamp when its called over both Blockchain and Block classes.
Currently, BlockChain::chain is an array with unknown size. But when you access chain[0] in BlockChain's constructor, you're assuming that chain points to valid memory, which it doesn't because you never initialize it. That's why you're getting a crash due to a bad memory access. I would suggest the use of std::vector<Block> instead of Block[], which you can resize as needed:
class BlockChain {
public:
std::vector<Block> chain;
BlockChain() {
// initialize and append a new block to chain
chain.emplace_back(createGenesisBlock());
}
my code:
#include <iostream>
using namespace std;
struct widget
{
char brand[20];
int type;
union id
{
long id_num;
char id_char[20];
}id_val;
};
int main()
{
widget prize =
{"Rolls", 0, "A2X"};
return 0;
}
The problem is with initialization "A2X" when initializing a union in a structure. Compiler doesn't know I want to choose second option with array of chars when I am passing "A2X", it's requiring long type. When I put
char id_char[20]
before
long id_num
everything is ok. But I want to know how to enforce compiler to accept "A2X" with char as the second option in union. Thank for your help.
But I want to know how to enforce compiler to accept "A2X" with char as the second option in union.
You can use a constructor:
id(char const *id_char) {
std::strcpy(this->id_char, id_char);
}
Alternatively you could use a widget constructor.
A drawback is that the compiler probably won't be able to warn you if you use a too large input string for initialization. The shown trivial constructor can be expanded with strlen to check overflow at runtime. I suggest throwing an exception if you choose to check.
This works with -std=c++11:
#include <cstring>
#include <stdexcept>
struct widget
{
char brand[20];
int type;
union id
{
long id_num;
char id_char[20];
}id_val;
widget(char const*Str, int Type, char const *Id);
};
widget::widget(char const*Str, int Type, char const *Id)
{
if (strlen(Str)+1 > sizeof brand)
throw std::length_error{"brand too large"};
memcpy(brand,Str,strlen(Str)+1);
type = Type;
if (strlen(Id)+1 > sizeof id_val.id_char)
throw std::length_error{"id too large"};
memcpy(id_val.id_char,Id,strlen(Id)+1);
}
int main()
{
widget prize = {"Rolls", 0, "A2X"};
return 0;
}
It seems this problem is the so-called dangling pointer problem. Basically I'm trying to parse a pointer into a function (that stores the pointer as a global variable) inside a class, and I want the pointer to be stored in that class and can be used now and then. So from inside the class, I can manipulate this pointer and its value which is outside of the class.
I simplified the code and re-created the situation as the following:
main.cpp
#include <iostream>
#include "class.h"
using namespace std;
void main() {
dp dp1;
int input = 3;
int *pointer = &input;
dp1.store(pointer);
dp1.multiply();
}
class.h
#pragma once
#include <iostream>
using namespace std;
class dp {
public:
void store(int *num); // It stores the incoming pointer.
void multiply(); // It multiplies whatever is contained at the address pointed by the incoming pointer.
void print();
private:
int *stored_input; // I want to store the incoming pointer so it can be used in the class now and then.
};
class.cpp
#include <iostream>
#include "class.h"
using namespace std;
void dp::store(int *num) {
*stored_input = *num;
}
void dp::multiply() {
*stored_input *= 10;
print();
}
void dp::print() {
cout << *stored_input << "\n";
}
There is no compile error but after running it, it crashes.
It says:
Unhandled exception thrown: write access violation.
this->stored_input was 0xCCCCCCCC.
If there is a handler for this exception, the program may be safely continued.
I pressed "break" and it breaks at the 7th line of class.cpp:
*stored_input = *num;
It is not a dangling pointer, but a not initialized, you probably want:
void dp::store(int *num) {
stored_input = num;
}
I am learning classes and OOP, so I was doing some practice programs, when I came across the weirdest bug ever while programming.
So, I have the following files, beginning by my class "pessoa", located in pessoa.h:
#pragma once
#include <string>
#include <iostream>
using namespace std;
class pessoa {
public:
//constructor (nome do aluno, data de nascimento)
pessoa(string newname="asffaf", unsigned int newdate=1996): name(newname), DataN(newdate){};
void SetName(string a); //set name
void SetBornDate(unsigned int ); //nascimento
string GetName(); //get name
unsigned int GetBornDate();
virtual void Print(){}; // print
private:
string name; //nome
unsigned int DataN; //data de nascimento
};
Whose functions are defined in pessoa.cpp
#include "pessoa.h"
string pessoa::GetName ()
{
return name;
}
void pessoa::SetName(string a)
{
name = a;
}
unsigned int pessoa::GetBornDate()
{
return DataN;
}
void pessoa::SetBornDate(unsigned int n)
{
DataN=n;
}
A function, DoArray, declared in DoArray.h, and defined in the file DoArray.cpp:
pessoa** DoArray(int n)
{
pessoa* p= new pessoa[n];
pessoa** pointer= &p;
return pointer;
}
And the main file:
#include <string>
#include <iostream>
#include "pessoa.h"
#include "DoArray.h"
#include <cstdio>
using namespace std;
int main()
{
//pessoa P[10];
//cout << P[5].GetBornDate();
pessoa** a=DoArray(5);
cerr << endl << a[0][3].GetBornDate() << endl;
cerr << endl << a[0][3].GetName() << endl;
return 0;
}
The weird find is, if I comment one of the methods above, "GetBornDate" or GetName, and run, the non-commented method will run fine and as supposed. However, if both are not commented, then the first will run and the program will crash before the 2nd method.
Sorry for the long post.
Let's look into this function:
int *get()
{
int i = 0;
return &i;
}
what is the problem with it? It is returning pointer to a local variable, which does not exist anymore when function get() terminates ie it returns dangling pointer. Now your code:
pessoa** DoArray(int n)
{
pessoa* p= new pessoa[n];
return &p;
}
do you see the problem?
To clarify even more:
typedef pessoa * pessoa_ptr;
pessoa_ptr* DoArray(int n)
{
pessoa_ptr p= whatever;
return &p;
}
you need to understand that whatever you assign to p does not change lifetime of p itself. Pointer is the same variable as others.