execl - No memory available to program now (OS X / XCode / C++) - c++

I'm trying to execute a very simple program that runs "ls" command
Im working under Mac OS 10.7, with XCode and C++
This is the code:
#include <iostream>
using namespace std;
int main(void)
{
cout << "Hello world" << endl;
execl("/bin/ls","ls",NULL);
return 0;
}
It crashes after following output
Hello world
No memory available to program now: unsafe to call malloc
I tried to google it but no luck, any ideas on what I might be doing wrong?

This is just "my opinion"
From man page:
The exec family of functions replaces the current process image with a
new process image.
It could be that it tries to replace the debugger process and so it crashes (the app is run from Xcode..). If you execute the app from command line it works...

Seems to work fine:
http://ideone.com/8AoZ3
But seems like on your platform some sort of weird recursion is taking place. Can you change your call to:
execl("/bin/ls","/bin/ls",0);

I know this may not be exactly what you want to do, but the following SO question is using execv to execute echo:
how-to-create-a-process-on-mac-os-using-fork-and-exec

Related

GDB Skips While Loop Condition When Used With File Input

Alright Stack Overflow, I am running into a decently persistent problem in my C++ code. I'm sure this is one of those dumb mistake moments, but I have tried everything and cannot seem to squish this bug.
I have a bit of code here, and it's behavior is very odd. I have a main function that opens a file containing text I want to read in. I was taught in programming fundamentals class at my university that I could use getline() as a condition for the while loop, which is nice since it automatically terminates when it reaches the end of the file.
#include <iostream>
#include <fstream>
using namespace std;
int main()
{
fstream input_mem_traces("gcc.txt");
string trace_to_parse = "";
while(getline(input_mem_traces, trace_to_parse))
{
cout << trace_to_parse << endl;
}
}
When I compile and run it, it works just fine. It reads out every single line of the file I pass it, and returns with no problems.
However, when I try to use gdb, and set a breakpoint at the line
cout << trace_to_parse << endl;
it didn't hit the breakpoint. Curious as to why that was, I broke above the loop, and tried single stepping through the code. When I got to the while loop, and tried to step, it simply skipped to the line after it, which happened to be the end of the program.
This behavior occurs both using the VSCode GUI front end for gdb, as well as straight gdb from the command line. I am running this on Windows using Ubuntu under WSL2, and VSCode as my IDE with the Remote - WSL extension enabled.
Turns out there was some weirdness going on with the working directory with GDB. For some reason, my working directory was changing under the VSCode GUI, thus the file was not able to be opened, and the while loop condition performed as expected for that circumstance by not entering the loop. Upon the recommendation by Retired Ninja in the comments, I used an absolute path in the fstream object constructor, and that solved the issue.

Why is the console asking for input even though there is no input in code?

I'm taking an online computer science class for grade 12 and we're using c++. I've never touched c++ and I'm starting to wish I never had. The teacher is comparing c++ to java (a language I can use perfectly fine) and we're currently learning how to input and output strings and chars. The simple practice problem was
Use one of fputc(), putc(), or putchar() to print your name one char at a time.
Since I have no clue how to use fputc() or putc() I decided to go with putchar()
#include <iostream>
using namespace std;
#include <stdio.h>
int main() {
cout << "My name is :" << endl;
putchar('J');
putchar('a');
putchar('c');
putchar('o');
putchar('b');
return 0;
}
I tried just using putchar(), and then added the cout, and have tried restarting eclipse, etc. but every time I run the program, the console asks for an input. There should not be an input for this program at all.
Try running your program from outside of the IDE and see what happens. When you launch a console program from inside of an IDE, a new console window is created to run the program in. When the program ends, the console window will close. Many IDEs setup the console to wait for you to press a key, giving you a chance to see the program's output, before the window closes.

How to exit GNU Octave, after running an m file, without closing plot windows?

I have been writing a C++ program to solve the problem of the simple pendulum and then plot the result using GNU Octave. It plots the result via this line in my program:
system("./simppenadj.sh");
where simppenadj.sh is:
#!/bin/sh
octave --no-gui --persist -q simppenadj.m
and simppenadj.m is:
#!/usr/bin/octave
# Plotting simppenadj.txt
A = importdata('simppenadj.txt');
B = importdata('simppenadjdx.txt');
t = A(:,1);
theta = A(:,2);
dtheta = B(:,2);
figure
plot(t,theta)
xlabel('t','FontSize',16,'FontWeight','bold')
ylabel('\theta','FontSize',16,'FontWeight','bold')
title('{d^{2}\theta}/{d{t^{2}}} = -9.8 cos({\theta})','FontSize',18,'FontWeight','bold')
figure
plot(theta,dtheta)
xlabel('\theta','FontSize',16,'FontWeight','bold')
ylabel('d\theta/dt','FontSize',16,'FontWeight','bold')
title('{d^{2}\theta}/{d{t^{2}}} = -9.8 cos({\theta})','FontSize',18,'FontWeight','bold')
Whenever I run my C++ program the CLI of GNU Octave is started (and left opened at the end) and the data is plotted. I do not want the CLI of GNU Octave to be left open, but the only way I know how to get it not to open is to remove the --persist option in simppenadj.sh which also makes the plots generated by GNU Octave to not be left open. This is a problem, as I want the plots to be left opened after my C++ program has been run. So is there a way to do this?
You can use the octave API to call the script from within your program. There, create a child process, which calls octave, so the parent process can end. With this, you can keep octave running. With this method, there is no octave CLI, since you do all calls to octave via the API, especially feval.
Unfortunately, the guide on using the API is very bad, but i put something together for you which should work. It basically only reads a script and executes the corresponding function. This is the nice thing about this method: you can write everything using normal octave function/script file methods.
I added the printf statement in the octave file in order to show how you can pass arguments to octave.
main.cpp
#include <iostream>
#include <unistd.h>
#include <octave/oct.h>
#include <octave/octave.h>
#include <octave/parse.h>
#include <octave/toplev.h>
int main()
{
pid_t pid = fork();
if(pid != 0) // parent
{
std::cout << "parent, exiting\n";
}
else
{
// arguments for octave
string_vector argv (2);
argv(0) = "embedded";
argv(1) = "-q"; // quiet
// start octave, run embedded (third parameter == true)
octave_main (2, argv.c_str_vec (), true);
// read the script file
source_file("calc_and_plot.m");
// call the function with an argument
octave_value_list in;
in(0) = "Hello, world.";
feval("calc_and_plot", in);
std::cout << "octave (child process) done\n";
clean_up_and_exit(0); // quit octave. This also quits the program,
// so use this together with atexit, if you
// need to do something else after octave exits
}
return 0;
}
octave script/function file
function calc_and_plot(str)
printf('%s\n', str);
x = linspace(0, 2*pi, 100);
y = sin(x);
it = plot(y);
waitfor(it);
end
Compile the main.cpp with
g++ main.cpp -L/usr/lib/octave-4.0.2 -I/usr/include/octave-4.0.2 -loctave -loctinterp
You have to adjust the paths to your system and octave version. You can also use the mkoctfile command, which basically does the same. You can look at the output of its -p switch, e.g.
mkoctfile -p CFLAGS
to get the libs, compiler flags etc. Have a look at the manpage for this.
I'm assuming you have the following problem:
Keeping persist results in an octave prompt, which stops the rest of your c++ program from running until you exit.
Removing persist closes the figures, but then the rest of your c++ program runs normally.
Assuming you're on a linux terminal, this is more of a hack, but you could just add a pause command on your octave file (actually a small pause followed by an indefinite pause if you want to make sure all images are flushed), and then call your script from c++ with a "&" at the end, which makes it go into 'daemon' mode.
The result of this is that the octave code will run in the background, meaning your plots stay up, and your c++ program doesn't halt.
Having said that, the plots will close once your c++ program exits. If you don't want that either and you want the plots to stay open even after your c++ program has "finished", then you can hack even further using a pause() or sigsuspend() function at the end of your c++ code too, and then call your c executable with a & too. (and once you're done playing, kill it manually from your terminal, or just exit your terminal)

C++ in VSCode - Getting Started

I'm having trouble getting a simple C++ script to run in VSCode (I'm new to both). I followed these instructions, and the status bar displays "C++" on the bottom right of the screen, next to the smiley face. I then ran the following script:
#include <iostream>
using namespace std;
main()
{
cout << "Hello World!\n";
return 0;
}
When I run it, the script's path flashes on the output screen and disappears. I expected it to display "Hello World" in the output.
I can run the script from the command window (I'm in Ubuntu) and the output file behaves as expected when executed.
Your program prints message to STDOUT and exits. Add some kind of wait (you can read STDIN for example) if you want to see its output.
PS: Why do you call your program "script"?

Why does my simple hello world C++ app use 3 threads?

When I look in windows task manage it says it's using 3 threads? Why is this? I was expecting just 1 thread to be used.
I used Netbeans IDE and MinGW-Windows g++ to compile it.
Thanks
Code:
#include <iostream>
using namespace std;
int main() {
cout << "Hello World";
int input;
cin >> input;
return (EXIT_SUCCESS);
}
Maybe Netbeans put some wrapper for internal purpose ? (debugging, profilling, ...) Anyway it don't matter because you didn't create it : these threads should not interfere with your program and your program will not interfere with them.
I don't use Task Manager or Netbeans, but can I suggest you may have misread the output:
one thread to start a shell
one thread for the shell to execute your program
one thread for your program's executable
Total 3. None except the last have anything to do with C++.