c++ 'new' and 'this' return different addresses

S

Skrunk

Guest
Skrunk Asks: c++ 'new' and 'this' return different addresses
I have some code similar to this:

Code:
#include <iostream>

class Grandparent
{
public:
    virtual void foo() {};
};

class Parent : public Grandparent
{
public:
    virtual void bar() {};
};

class Child : public Parent
{
public:
    Child(Child** out)
    {
        *out = this;
    }
    
    void foo() override {};
};

Child* create1()
{
    Child* p;
    new Child(&p);
    return p;
}

Child* create2()
{
    Child* p;
    return new Child(&p);
}

int main()
{
    Grandparent* a = create1();
    
    if (!dynamic_cast<Parent*>(a))
    {
        std::cout << "bad cast (create1)" << std::endl;
    }
    else
    {
        std::cout << "good cast (create1)" << std::endl;
    }
    
    Grandparent* b = create2();
    
    if (!dynamic_cast<Parent*>(b))
    {
        std::cout << "bad cast (create2)" << std::endl;
    }
    else
    {
        std::cout << "good cast (create2)" << std::endl;
    }
    
    return 0;
}

The problem is that sometimes this segfaults on dynamic_cast<Parent*>(b). Seemingly unrelated code changes (such as adding a class definition, even if unused) can change whether a segfault occurs.

It's possible this is expected behavior, and that this doesn't necessarily point to the beginning of the memory allocated for the object by new. But then why is a consistently downcastable, and b is not?

The simplified code above does not trigger this problem. In production code Child and create are defined in a shared library (create is declared extern "C"), the library is loaded with dlopen, and create is located with dlsym.

Other possibly relevant details:

  • The shared library and the executable both link to a common library where Grandparent and Parent are defined.
  • The vtable for a is always good, but the vtable for b is corrupt when the segfault occurs. It still has the right number of entries, but the memory is either unreadable, or contains pointers to functions in completely different classes.
  • The value of b seems to always end in 00 (eg. 0x23ab00), while the value of a does not (eg. 0x23ab38). I have never seen the addresses be more than 64 bytes apart.

SolveForum.com may not be responsible for the answers or solutions given to any question asked by the users. All Answers or responses are user generated answers and we do not have proof of its validity or correctness. Please vote for the answer that helped you in order to help others find out which is the most helpful answer. Questions labeled as solved may be solved or may not be solved depending on the type of question and the date posted for some posts may be scheduled to be deleted periodically. Do not hesitate to share your thoughts here to help others.
 
/forums/whats-new/news-feed

Unreplied Posts

NodeJS, express validator working fine in routes, but error when importing from controllers

mughil singh Asks: NodeJS, express validator working fine in routes, but error when importing from controllers
To brief I am new to NodeJS and am trying to make a signup page with backend validation, the tool for the job I am using is express-validator. The validation works fine when I type it into the routes file, however I am trying to split the code into a controller file and I am getting issues, It is telling me that a comma should not be a certain point when I use it in the controller file but when I use it in the routes file it works fine, I know the code is correctly being imported as I also render the page with the same route/controller pair (I have omitted that part of the code for brevity)

SignupRoutes.js

Code:
const express = require('express');
const router = express.Router();

const signupController = require('../controllers/signupController');
router.post('/', signupController.serverSideEmailValidation);

module.exports = router;

signupController.js (Line 6 is the error, the comma at the end of the line)

Code:
const { check, validationResult } = require('express-validator');
const User = require('../models/userModel');
const serverSideEmailValidation = 
check('email')
    .notEmpty().withMessage('Email cannot be empty')
    .isEmail().withMessage('Email is invalid'),
    (req, res) => {

    const errors = validationResult(req);
    if(!errors.isEmpty()){
        return res.status(400).json({errors: errors.array()});

    };
    const user = new User({
        email: req.body.email,
        password: req.body.password
    }); 

    user.save();
    res.redirect('verify-email');
    };

module.exports = {serverSideEmailValidation}

Thanks for your time

SolveForum.com may not be responsible for the answers or solutions given to any question asked by the users. All Answers or responses are user generated answers and we do not have proof of its validity or correctness. Please vote for the answer that helped you in order to help others find out which is the most helpful answer. Questions labeled as solved may be solved or may not be solved depending on the type of question and the date posted for some posts may be scheduled to be deleted periodically. Do not hesitate to share your thoughts here to help others.

Peculiar performance variance with small arrays

Canleskis Asks: Peculiar performance variance with small arrays
as part of a larger project (of N-body simulations) I started working with arrays using const generics to represent algebraic vectors. Those vectors can then be of any size, but I'm especially interested in the ones of length 2 and 3.

I noticed that performance with arrays of length 2 was worse (a lot worse!) compared to similarly sized arrays (length 1 or 3 for example) in a certain scenario I need for my project.

This is the scenario, or rather a shortened version of it:

Code:
fn fold<const N: usize>(v: Vec<Array<N>>) -> Vec<Array<N>> {
    let result = v.iter().map(|a1| {
        v.iter().fold(Array::default(), |acc, a2| {
            let d = *a2 - *a1;

            acc + d
        })
    });

    result.collect()
}

The arrays are wrapped in a newtype called Array implementing operators for simplicity, but the results are the same without that wrapper.

Using criterion with Vecs lengthed from 10 to 500 of random arrays, I benched this function and generated the following graph for differently sized arrays:
1


As you can see performance is a lot worse for arrays of length 2 compared to the rest. I'm unable to understand why this specific scenario leads to such performance variance, so I'm hoping someone can help me figure this out because this has slowed down my progress significantly.

SolveForum.com may not be responsible for the answers or solutions given to any question asked by the users. All Answers or responses are user generated answers and we do not have proof of its validity or correctness. Please vote for the answer that helped you in order to help others find out which is the most helpful answer. Questions labeled as solved may be solved or may not be solved depending on the type of question and the date posted for some posts may be scheduled to be deleted periodically. Do not hesitate to share your thoughts here to help others.

Using ReadDirectoryChangesW() to get information about new files in a folder

LUN2 Asks: Using ReadDirectoryChangesW() to get information about new files in a folder
Good evening!

I need to get information about new files in certain directory (Windows 10, C++).

To do this (1) I call ReadDirectoryChangesW in overlapped mode and point an event to be signaled when ReadDirectoryChangesW will finish, (2) wait until event will be signalled (WaitForMultipleObjects), (3) call GetOverlappedResult to get ReadDirectoryChangesW info about new files.

All actions above are repeated in a loop.

It works well, but if I create two or more files simultaneously (copy several files and paste them in the Windows Explorer), then in the step (3) I get info about one file only.

But if I rename a file, then I correctly get from ReadDirectoryChangesW two records – about old and new file names.

Buffer (FILE_NOTIFY_INFORMATION) for ReadDirectoryChangesW likely does not overflow – I allocate 10 kb, information about new files is about 50-200 bytes (their paths and names are short enough).

If I do copy/paste 1 file, then 1 file etc, than each copying is reported normally.

It seems ReadDirectoryChangesW/GetOverlappedResult return info about 1 file only if new files appear "fast" (copy/paste several files), but how can I get info about other files ?

SolveForum.com may not be responsible for the answers or solutions given to any question asked by the users. All Answers or responses are user generated answers and we do not have proof of its validity or correctness. Please vote for the answer that helped you in order to help others find out which is the most helpful answer. Questions labeled as solved may be solved or may not be solved depending on the type of question and the date posted for some posts may be scheduled to be deleted periodically. Do not hesitate to share your thoughts here to help others.

how to install azure functions on apple M1 pro, facing issues when installed with Rosetta

Onki Asks: how to install azure functions on apple M1 pro, facing issues when installed with Rosetta
I just had my first Mac book but that too with M1 processor and since then I am struggling with software compatibility issues.

Considering that I dont have much experience with Mac, I really need some help in resolving this issue.

I want to run azure functions on VS Code locally and for that, I need python, VS Code and azure tools but I kept on getting errors saying that Architecture ARM is not supported for language python.

I tried with python 3.8, 3.9 and 3.10 (3.10 was not accepted by VS Code.)

So, now what I understand is that using Rosetta, we can use the same softwares which we use on intel processor, so I followed below protocol for that.

  1. installed Rosetta : /usr/sbin/softwareupdate --install-rosetta
  2. /bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)"
  3. cd ~/Downloads
  4. mkdir homebrew
  5. curl -L https://github.com/Homebrew/brew/tarball/master | tar xz --strip 1 -C homebrew
  6. sudo mv homebrew /usr/local/homebrew
  7. export PATH=$HOME/bin:/usr/local/bin:$PATH
  8. Let’s add an alias and path in the ~/.zshrc file:

-If you come from bash you might have to change your $PATH.

-need this for x86_64 brew

export PATH=$HOME/bin:/usr/local/bin:$PATH alias axbrew='arch -x86_64 /usr/local/homebrew/bin/brew'

LINK I referred for this: How to Install x86_64 Homebrew Packages on Apple M1 MacBook

  1. Now you can install apps for Intel processors: axbrew install package-name

so, now I thought I am finally done.

  1. I installed python -> axbrew install python@3.9
  2. I downloaded VS Code Universal.
  3. ran the function, it threw error for "you must have download azure function core tools". Used below commands to download it : [IMG alt="-[![enter image description here][1]][1]
    [![enter image description here][2]][2]"]https://i.stack.imgur.com/u7V98.png[/IMG]

but still I keep getting this error from VS Code. VS code doesnt recognize the azure tools functions I installed.

I tried with VSCode universal, for intel etc, but still the same.

Any leads on why I am facing this issue and how to come out of it.

VS Code error

SolveForum.com may not be responsible for the answers or solutions given to any question asked by the users. All Answers or responses are user generated answers and we do not have proof of its validity or correctness. Please vote for the answer that helped you in order to help others find out which is the most helpful answer. Questions labeled as solved may be solved or may not be solved depending on the type of question and the date posted for some posts may be scheduled to be deleted periodically. Do not hesitate to share your thoughts here to help others.

MAUI Draw line on canvas during runtime after button click

Aj Johnson Asks: MAUI Draw line on canvas during runtime after button click
I want to draw a new line in a GraphicsView after the click of a button. This will draw the line on startup but I would like to either redraw the current line or preferably add another line to the view.

Code:
<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://schemas.microsoft.com/dotnet/2021/maui"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             xmlns:controls="clr-namespace:CoachesToolbox.Controls"
             xmlns:viewmodel="clr-namespace:CoachesToolbox.ViewModel"
             xmlns:mct="http://schemas.microsoft.com/dotnet/2022/maui/toolkit"
             xmlns:drawable="clr-namespace:CoachesToolbox.Models"
             x:DataType="viewmodel:MainViewModel"
             x:Class="CoachesToolbox.Views.MainPage"
             Title="CoachesToolBox demos"
             >
    <ContentPage.Resources>
        <drawable:Drawable x:Key="MyDrawable" />

    </ContentPage.Resources>

Code:
<GraphicsView x:Name="Canvas"
                          HorizontalOptions="Fill"
                          VerticalOptions="Fill"
                          Drawable="{StaticResource MyDrawable}"
                          Grid.Column="1"
                          Grid.Row="0"
                          BackgroundColor="Transparent"/>

Code:
namespace CoachesToolbox.Models
{
    public class Drawable : IDrawable
    {
        public void Draw(ICanvas canvas, RectF dirtyRect)
        {
            canvas.StrokeColor = Colors.Red;
            canvas.StrokeSize = 5;
            canvas.DrawLine(10, 10, 90, 100);
        }
    }
}

SolveForum.com may not be responsible for the answers or solutions given to any question asked by the users. All Answers or responses are user generated answers and we do not have proof of its validity or correctness. Please vote for the answer that helped you in order to help others find out which is the most helpful answer. Questions labeled as solved may be solved or may not be solved depending on the type of question and the date posted for some posts may be scheduled to be deleted periodically. Do not hesitate to share your thoughts here to help others.

Latest posts

Top