Comp Sci How to debug an infinite loop in a C++ program using fork gymnastics?

AI Thread Summary
The discussion centers on debugging an infinite loop in a C++ program that attempts to reverse a string using fork operations. The issue arises from the index decrementing without a defined stopping condition, leading to an infinite loop as the index continues to decrease past zero. Participants highlight that the program lacks a mechanism to terminate the recursion when the index reaches zero, which is essential for preventing the infinite loop. Additionally, one user notes compatibility issues with the <unistd.h> header file in Visual Studio 2015, which complicates debugging efforts. The conversation emphasizes the importance of properly managing recursion and index bounds in C++ programs.
carl123
Messages
55
Reaction score
0
7.JPG

note.JPG


This is what I did but I'm getting an infinite loop of the reversed string whenever I run the program. I don't know why

C:
#include <stdio.h> 
#include <stdlib.h>
#include <string.h>
#include <unistd.h> /* for fork() and getpid() */
#include <sys/types.h>
#include <iostream>
using namespace std;
string result;
void print(string s, int index){
   pid_t pid;
   pid = fork();
   if(pid == 0){
       //child
       cout<<s[index];
       index--;
       print(s,index);
       exit(0);
   }
   else if (pid < 0){
       cout<<s[index];
       index--;
       print(s,index);
       exit(0);
   }
   else{
       cout<<s[index];
       index--;
       exit(0);
   }
}
int main(){
   string s;
   int length;
   cout<<"Enter string to invert\n";
   cin>>s;
   cout<<"Reverse String: \n";
   print(s,s.size()-1);
}
 
Last edited by a moderator:
Physics news on Phys.org
looks like index decrements without bound...
 
  • Like
Likes FactChecker
Dr Transport said:
looks like index decrements without bound...
Can you explain what you mean sorry?
 
index-- has no lower bound, in other words how does it know when to stop when it gets to 0? I can't help you trace it because I do not have <unistd.h>...i.e. it isn't a part of Visual Studio 2015...
 

Similar threads

Replies
2
Views
2K
Replies
3
Views
2K
Replies
2
Views
2K
Replies
15
Views
3K
Replies
2
Views
2K
Replies
9
Views
3K
Replies
4
Views
1K
Replies
7
Views
2K
Replies
6
Views
3K
Back
Top