You can allocate an array in stack using stackalloc keyword, seems like it will satisfy your stack allocation needs. Unfortunately it requires you to be in unsafe context. int* block = stackalloc int[100]; ...
"Hence I do not know how and where to delete all these objects!" The best solution would be to get rid of calling delete yourself at all, but leave that to an appropriate smart pointer, e.g. class node { public: std::string gameState; std::unique_ptr<node> nextGameState; }; and all the other...
Stack* myStack = new Stack(10); ... delete myStack; Alternatively declare myStack on the stack Stack myStack(10); Also look into std::unqiue_ptr so you don't have to write delete myStack....
algorithm,data-structures,stack,queue
A doubly linked list, has all the computational complexity attributes you desire, but poor cache locality. A ring buffer (array) that allows for appending and removing at head and tail has the same complexity characteristics. It uses a dynamic array and requires reallocation, once the number of elements grows beyond...
Thanks guys, I fixed it.. works fine. thanks for all ur suggestions. #include<stdio.h> #include<malloc.h> #include<stdlib.h> struct stack { int * a; int top; int maxSize; }; void initstack(struct stack * p, int maxSize); void push(struct stack * p, int item); int pop(struct stack * p); void display(struct stack p); int...
Common routine is to store value of BP register in stack after procedure call. Then set BP to top of stack. After than you can access elements in stack using BP. nameOfProc proc push BP mov BP,SP stack than looks like this: ret address | BP register | <-- BP...
This is how you can get these: library(raster) b <- brick(system.file("external/rlogo.grd", package="raster")) minValue(b) # [1] 0 0 0 maxValue(b) # [1] 255 255 255 ...
The right way in go to implement a stack is simply to use a slice. stack := []*HuffmanTree{} You can push to the stack using append, and pop by writing: v, stack := stack[len(stack)-1], stack[:len(stack)-1] You could encapsulate it into its own type if you prefer, but a slice is...
It depends how your search (or which search algorithm) is implemented. Stack or Queue may also helpful for some searching application like - BFS, DFS. But in normal case when you are using linear search you can consider about array or ArrayList.
assembly,stack,stack-overflow,8086
If you're not allowed to modify the code then search for a 0CBh or 0CAh byte anywhere in the code segment. These are far return instructions, but they don't actually have used for that purpose by the code. You just need to find a byte with either of these values....
c++,recursion,stack,heap,stack-overflow
If you must use recursion, then put those recyclable variables inside a struct, and pass that reusable struct instance (instantiated at the outermost layer of recursion) by reference to your recursive calls.
c,recursion,stack,abstract-syntax-tree
Let's start right in the middle: }else{ /* if AST already has elements in it. */ tmp = AST; tmp -> left = tmp-> right = NULL; AST->datum = atol(argv[i]); AST->right = create_node(stack->datum); stack = pop(stack); AST->left = tmp; /*This puts the new operator as the root of the tree,...
Is the condition i < s.size() changing as the stack size changes ? Yes, because i increases while at the same time size() decreases. Walk through the logic in your head or on paper. for ( i = 0, size = 3 ) pop() ... i++ for ( i...
c,multidimensional-array,stack
I ultimately had to do a variation of Sascha's suggestion of using char **Array)[MAX_FILENAME_AND_PATHNAME_LEN] within an argument to the method. A working variation of my solution appears below. The reason I had to do it this way is because while I was able to dereference (**Array)[MAX_FILENAME_AND_PATHNAME_LEN] I was only able...
callback,stack,vm-implementation
I think I answered myself. The main point is that callbacks cannot arrive at any time (i.e. asynchronously). The reason is the one below. A callback is a simple user written C-style function that honors a calling convention. For example, in windows the CALLBACK type means stdcall. This means that...
c,x86,stack,argument-passing,calling-convention
Actually, I just compiled this function using GCC: int foo(int x) { goo(&x); return x; } And it generated this code: _foo: pushl %ebp movl %esp, %ebp subl $24, %esp leal 8(%ebp), %eax movl %eax, (%esp) call _goo movl 8(%ebp), %eax leave ret This is using GCC 4.9.2 (on 32-bit...
Here's my attempt at a recursive solution (see comments in Java code): private static int result = 0; private static int n = 3; public static void g(int right,int spur){ if (right == n) // all trains are on the right track result++; else if (right + spur < n)...
You shouldn't be returning a pointer to a local stack variable at all. Doing so is undefined behaviour, and the compiler is completely free to do whatever it wants. When you say unsafe, you are promising the compiler that you will manually uphold all of its expected invariants... and then...
Reading your code, tests, benchmarks, and results it's easy to see that they are flawed. A full code review is beyond the scope of StackOverflow. One specific bug. // Push pushes a new element to the stack func (s *Stack) Push(elem interface{}) { if len(s.slice)+1 == cap(s.slice) { slice :=...
You could do this with unstack as.data.frame(t(unstack(df1,par~id))) # V1 V2 V3 #a a1 a4 a7 #b a2 a5 a8 #c a3 a6 a9 Or using dcast after creating a sequence column for the 'id' group. library(data.table)#v1.9.5 dcast(setDT(df1)[, ind:= 1:.N, id], id~ind, value.var='par') ...
"First-in, last-out" is not always as descriptive for a new programmer as it might be for someone who has more programming experience. The concept of a stack - not, here, specifically referring to the C++ (or other-language) object - is a concept that permeates programming, at-large (a concept which is...
Both the difference and the why has to do with stack frames. The following link has a fairly good summary (if I do say so myself). What is stack frame in assembly?...
process,operating-system,stack,kernel,context-switch
I have a disagreement with the second paragraph. Process A is running and then is interrupted by the timer interrupt. The hardware saves its registers (onto its kernel stack) and enters the kernel (switching to kernel mode). I am not aware of a system that saves all the registers on...
Basically Ruby keeps a stack of things waiting for something, and it is getting too large: class FrancePresident def citizenship self.citizenship end end sarkozy = FrancePresident.new sarkozy.citizenship When the citizenship method is called, Ruby executes it. The execution is: call the citizenship method. Ruby does this about 10000 times before...
Take a look at the MIPS calling convention here. In particular, functions with four or fewer arguments pass the arguments in registers $a0,...,$a3. The stack pointer must always be four byte aligned, even when saving a value smaller than four bytes.
Stack supportStack = new Stack(); Stack is called a raw type: it's like not using generics. You need to use: Stack<T> supportStack = new Stack<T>(); But, as a hint: you don't need to do this. You can just do: return this.data.equals( s.data ); ...
java,eclipse,debugging,stack,mpi
Set an Eclipse breakpoint and launch the application in Debug mode. Then the IDE will be stopping at the breakpoint and you can step into mpi.jar library. If the source is not directly found you have to navigate and point Eclipse to it. Then you should be able to continue...
as title says, Where is Heap and Stack on Physical Memory? Ever since CPUs have had MMUs to add a layer of indirection between virtual memory and physical memory, heap and stack have been anywhere in physical memory. Ever since modern Operating Systems have implemented ASLR, heap and stack...
It's just a small error. In this code you look for '(' in the "in" array which makes no sense. You only want to look for it on the stack. else if(in[j]==')'){ int k=j; while(in[k]!='(' && !st.empty() ){ char ch=st.pop().toString().charAt(0); if(ch!='('&&ch!=')') out.append(ch); k--; } } Just change it to this...
graph,stack,scrollbar,amcharts
Just for the sake of sport I tried to implement it. Good news - it's possible :) First of all you will need to prepare both charts First chart Scrollbar enabled Chart cursor enabled Category axis hidden Legend disabled Bottom margin: 0 Second chart Scrollbar disabled Chart cursor enabled Category...
c++,multithreading,c++11,stack,lock-free
I'm not an expert in lock free programming, but I'm pretty sure that your code is NOT thread safe. Let's first look at register_idle(): What could happen here is that Thread1 increments idle_pos but before it stores its id, another thread calls wakeup_once and uses an outdated id (in the...
winapi,assembly,stack,x86-64,masm
mov dword ptr [rsp + 20h], 0 is wrong. The last parameter has the type LPOVERLAPPED, which is here a 64-bit pointer. Change the line to mov qword ptr [rsp + 20h], 0 Also, lea rcx, handle is wrong. WriteFile expects a value, not an address (pointer). Change it to...
For example, there's an iinc instruction which adds a constant value to the local variable like this: iinc 1, 8 This means "add 8 to the local variable #1". The constant 8 is directly written in the bytecode, following the iinc instruction code and constant 1: 0x84 0x01 0x08....
Even if a resource is plentiful, one should only use as much as one actually needs. 1MB is plenty large for the vast majority of applications, which makes it a very reasonable default. Since some programs may need more (e.g. deeply recursive algorithms), you are free to change the default...
linux,linux-kernel,stack,interrupt-handling,top-halves
All interrupts are handled by kernel. That is done by interrupt handler written for that particular interrupt. For Interrupt handler there is IRQ stack. The setup of an interrupt handler’s stacks is configuration option. The size of the kernel stack might not always be enough for the kernel work and...
stack,fortran,heap,stack-overflow,reshape
The Fortran standard does not speak about stack and heap at all, that is an implementation detail. In which part of memory something is placed and whether there are any limits is implementation defined. Therefore it is impossible to control the stack or heap behaviour from the Fortran code itself....
The 32 bit convention uses the cpu stack to pass floating point arguments. It only uses the fpu stack for returning them. Yes, you should convert your 32 bit float to a 64 bit double, as per the prototypes you provided. Note that ext_func is void, that is it doesn't...
1. set up a stack 2. scan the string char by char 2.1. for each left parenthesis "(" 2.1.1. push its location onto the stack 2.2. for each right parenthesis ")" 2.2.1. if stack is empty then 2.2.1.1. you have too many right parentheses 2.2.1.2. current location is first offending...
Here is how your stack could be implemented using a std::unique_ptr. Note the use of std::move() to re-assign the std::unique_ptr leaving the original pointing at nothing. Also, instead of if(topState == NULL) I have used the more idiomatic if(topState). A std::unique_ptr returns true if it points somewhere or false if...
process,linux-kernel,stack,kernel,scheduler
It depends on the OS but as a general rule there is a block of storage which holds information about each process (usually called the Process Control Block or PCB). This information includes a pointer to the current line of code that is being executed and the contents of registers...
Simple case for passing data to the GUI class MyData { // The data model }; class MyWindow: public FL_Window { MyData* m_data; public: void Data(MyData* data) { m_data = data; } ... }; int main() { MyWindow gui; MyData data; // Tell the gui about the data gui.Data(data); ......
In push: t->next = head->next head->next = t; Should be: t->next = head; head = t; What you want to do is first pretend like t is the new head, so you set the next pointer to point at the current head. If we imagine head is A and the...
Used a pre-sized stack array to keep things simple. When you want your data back, just call pop_balloon until the stack is empty (use the function). The following code is untested and pulled out of thin air, but it should show you want you need: Balloon balloonStack[MAX_NUM_BALLOONS_POSSBILE]; int balloonStackIndex =...
Since T cached is declared inside the method I assume it is allocated on the stack, right? T being allocated in a method doesn't effect it being on the heap or the stack. The decision whether it is the former or the latter is based on whether this is...
First, both of your function's signature are weird: void push(stack *start, stack *p, int s) void pop(stack *start, stack *p) Assuming start points to top of stack, you should discard p. It should be a local variable to the function, not a parameter. Second, let's see push implementation: p =...
From the very bottom of this page from the Swift Reference: NOTE The description above refers to the “copying” of strings, arrays, and dictionaries. The behavior you see in your code will always be as if a copy took place. However, Swift only performs an actual copy behind the scenes...
To fix the compiler error, you have two options as mentioned in my comment: Change stack* myData; to stack myData; Change myData.push(u); to myData->push(u); Preferable design is the 1st option. To make the 1st option work you should use the member initializer list of your constructor: class uses{ private: stack...
c++,arrays,stack,priority-queue
SortPrioQueue() should use top_ - _bottom (or num_items()) as limit and not size.
android,android-intent,android-activity,stack
If you know to which activity you want to go in onBackPressed() you can start the activity with the FLAG_ACTIVITY_CLEAR_TOP. It would switch to the instance of MenuActivity if an instance is existing, but it would also remove all activity instances which are between your current activity instance and the...
If you are trying to implement it this way that both stacks start from left side of the array. Push and pop won`t be O(1). Since the elements of both stacks will be intermixed among each other and you have to maintain whether a position belongs to stack1 or stack2...
You are using == to compare strings where you should be using .equals when detecting operators.
If you want to assign -1 to the pointer: s->top = -1; (should give a warning but will probably compile). If you want to assign -1 to the int top is pointing at *(s->top) = -1; will compile but probably crash since top is not pointing anywhere valid yet. int...
A recursive method (it doesn't really matter if it's recursive or not) can access static members of the class to which it belongs, as well as non static members (assuming the recursive method is not static). This data is in the heap. However, if you wish to mutate the array...
It seems like a local array (on the stack, perhaps?) is being passed to push() from the code below. locArr[0] = l->xloc; locArr[1] = l->yloc; push(s, locArr); But push() is storing a pointer to the local stack in items, not a copy of the local array, so it could be...
System.out.println is buffered whereas error output is not buffered. That means that there is occasionally a delay before you see the results from System.out.println. Exceptions are reported through System.err.println, which is not buffered and so prints immediately. Try switching your System.out.println statements to System.err.println, and see if the problem resolves....
The behavior might differ depends on whether you have an interpreted or JIT-compiled frame. In JIT-compiled frame the object can be marked as free after the last usage of the variable even if it's still in the scope. See this answer for example. In interpreted frames it will still reside...
windows-runtime,stack,async-await
The stack trace with the weird name tells you that the exception was thrown in the MoveNext() method of the <GetStudentKey>d__14a type. When you are using async and await the compiler generates some code to implement a state machine. This state machine involves a struct and in your case the...
c++,performance,stack,heap-memory
This has obviously nothing to do with "writing vs overwriting". Assuming your results are indeed correct, I can guess that your "faster" version can be vectorized (i.e. pipelined) by the compiler more efficiently. The difference in that in this version you allocate a storage space for temp, whereas each iteration...
algorithm,data-structures,stack
You popped a total number of 10-3 = 7 elements, since 3 of the pops did not change the state (and size) of the stack, so only 7 pops did. You pushed a total of 25 elements. Top operations do not change the state (and size) of the stack,...
The segmentation fault is probably caused by the fact you are freeing your top in the push function. You really don't want to do that, because the calling code is working with it. But there are some other flaws in the program. For example: The logic in the code is...
The GNU C library (glibc) will use __printf_chk instead of printf if you (or the the compiler) defines _FORTIFY_SOURCE and optimization is enabled. The _chk version of the function behaves just like the function it replaces except it's supposed to check for stack overflow and maybe validate the arguments. The...
c,pointers,types,stack,structure
A major problem is that you pass the stack structure by value to all functions, and that means that the structure is copied and all changes done inside the functions are made on the copies and not the original. C doesn't support passing by reference, but it can be emulated...
linux,linux-kernel,stack,kernel,interrupt
Kernel mode stack in Linux kernel is stored in task_struct->stack. Where and how it comes from is totally up to the platform. Some platforms might not be saving it like above. But then you can use task_stack_page() to find the stack. And While entering the interrupt handler, PC is stored...
The best thing to do would be increase the number of blocks of memory that get pushed onto your stack at one time. For example, if you are only expecting the user to enter in words that are equal to or less than 5 characters, then one "push" on your...
I'm using Windows & MSVC but you should get the idea. Consider the following code: #include <stdio.h> void someFunc() { puts("wow, we should never get here :|"); } // MSVC inlines this otherwise void __declspec(noinline) doit(void) { char buf[8]; gets(buf); printf("%s\n", buf); } int main(void) { printf("So... The End...\n"); doit();...
java,string,stack,heap,immutability
String is immutablabe means you cannot change the string value on the same address if you change it will create a new object and you have to assign it to the current string object Fo ex String a = "Hariom"; a.replace('H', 'b'); System.out.println(a); //will print Hariom because a is not...
c++,pointers,memory-management,stack,heap
The sequence is correct except one point: The delete []ip; removes the memory allocated on the heap to the ip pointer. The pointer that got passed through to myFun now points to nothing. The pointer doesn't point to 'nothing' (i.e. isn't set to nullptr or 0 after freeing the memory)....
c++,memory,dynamic,stack,difference
The both stacks use dynamically allocated memory for their nodes (though for std::stack it depends on underlying container). Of course it is better to use standard class. It was already tested and written by qualified programmers and it is flexible enough: you can use several standard containers to implement the...
c++,templates,linked-list,stack
Almost no popular compiler allow you to put template definition in cpp file as a separated compilation unit (hence the linker errors). In brief, just move the content of your Stack.cpp into Stack.h (and forget about your Stack.cpp) then everything should work. Another way I like to use (well... over...
Now we run clickBack... Why does the alert output "Home"??` because stackBack[0] is Home. What would you expect it to do? You even have it in your question: stackback = ['Home','CentralPortfolio'] The index 0 is the first element in your array, which is Home. The last element is stackBack[stackBack.length...
stack(4) // returns 5th element stack.last // returns last element Those operations are constant time....
function,swift,memory,stack,heap
Both classes and closures are reference types. var foo = Foo() creates a Foo object on the heap, and stores a (strong) reference to that object in the local stack variable foo. return { foo } creates a closure which captures foo, so that the closure holds another (strong) reference...
There are a lot of bugs in your code because of the way you are treating nextPos and curPos. In particular, this line: nextPos = currPos; Here you are assigning nextPos to be the same array as curPos, so if you modify one, the other one will be modified along...
Q: I haven't been able to think of a way to keep the stack the way it is A: A: That's because reading from a "classic" stack is destructive. "Reading" an element == removing that element from the stack. TWO SOLUTIONS: 1) Modify your stack implementation so that you can...
Because using a dynamically allocated array, you may choose to expand it (allocate a larger array when needed) or to minimize it (free some memory to reduce RAM usage). What you'd be probably referring to is malloc, realloc and free. What you'd want to do is to allocate some memory...
c,linux,memory,stack,portability
Q 1. why is ch empty even after fread() assignment? (Most probably) because fread() failed. See the detailed answer below. Q 2.Is this a portability issue between Solaris and Linux? No, there is a possible issue with your code itself, which is correctly reported by valgrind. I cannot quite...
Code needs to replicate str in push_ch(int id, char *str) Example: char *str_dup = strdup(str); ... temp->c_name = str_dup; ... temp->next->c_name = str_dup; If strdup() unavailable, make your own char *my_strdup(const char *s) { if (s) { size_t length = strlen(s) + 1; char *newptr = malloc(length); if (newptr) {...
1) Default copy constructor operator: Stack s2(s1) correcsponds to the Stack s2(const Stack& x) copy constructor, generated by your compiler if you don't tell him to use another one. 2) Definition of a member function StackIter *Stack::createIterator()const { ...} is the definition of the member function createIterator() that is declared...
for (i = 0; i < 2; i++) { ... pushStack (stack, &i); // Push address of i } You are pushing (same) address of i twice. Which after loop end contains 2. When you pop back, you get the address which contains 2 and hence the output is 2...
The thing you are trying to do is usually made with stack data structure: E.g. see simple implementation: // create a stack named history var history = [] // ... // when a folder is expanded - add it to the stack history.push(currentfolder) // when going back - remove the...
You first have to install and load the raster package: install.packages("raster", dependencies=TRUE) library(raster) Then change your working directory to the file location: setwd("M:/2009_stack") Create a raster stack out of your files: myStack <- stack(list.files(pattern="\\.img$")) If you want to export an .IMG file into your working directory: writeRaster(myStack,"mod11a1_2009_lst_day_1km.img", format="HFA") For more...
javascript,recursion,stack,intern
The easy way to perform recursion in a Command chain (or any Promise chain, actually!) is to hold your stack in closure, then call the method that does the work recursively as a Promise callback until your stack is exhausted. Once the stack is resolved undefined will be returned by...
Since you are using cygwin this is very easy with getrlimit #include <stdio.h> #include <sys/resource.h> #include <sys/time.h> int main(void) { struct rlimit rl; if (getrlimit(RLIMIT_STACK, &rl) != 0) return -1; fprintf(stdout, "current: %ld kB\n\n", rl.rlim_cur / 1024); return 0; } ...
First of all, you are aware that C++ has std::stack built in, aren't you? For the rest of the answer, I'll assume that you have some reason not to use it (perhaps it's a learning exercise). A very naïve way to achieve what you want would be: On every addition...
assembly,compilation,stack,compiler-optimization
In general, you can only use the stack above the stack pointer. The stack pointer defines the end of the stack. Accessing under the stack pointer may or may not work. It especially won't work if you call another function, since the return address would be pushed and also the...
c#,exception,memory,stack,out-of-memory
A few things to consider. The architecture (32 bit / 64 bit) that you are targeting. Like this answer said already, try compiling for a 64 bit platform if that is an option. 32-bit .NET processes are limited to 2 GB no matter how much RAM your machine's got. You...
In Node::Node you are shadowing the member variable a, int a = b; replace it by a = b; or better, use a constructor initializer list Node(int b): a(b), next(NULL){} ...
java,generics,constructor,stack
The problem for both your constructors is that you have put a return type of void. You cannot have a return type on constructors. That is why the constructor is not found and compiler thinks there is only a default constructor.
Your first condition in the closing brackets block checks whether your stack has the size != 1. I assume this is meant to check that you don't have any leftover opening brackets, which is a good idea. However, you'll miss this entire check if your last char isn't a closing...
@RyanP really deserves credit for this answer. After looking at his suggestion, when I fixed the code to... while (bmess [i] != '/O'){ palinS.push(bmess [i]); palinQ.front(bmess [i]); i++; } That solved my problem of the never-ending Stack & Queue 'list' creation. Thanks for all the comments!...
The push operation adds a new item to the top of the stack. In this implementation, the top of the stack is s->top. The second item on the stack is s->top->next, the third is s->top->next->next, and so on. I think it is easier to think of n->next = s->top; s->top...
android,android-viewpager,stack,carousel
You have to create your own carousel like this.Please check StackView and ViewFlipper also.
The current() function will give you the 'current' array-value. If you're not sure if your code has begun to iterate over the array, you can use reset() instead - but this will reset the iterator, which is a side-effect - which will also give you the first item. Like this:...
c,multithreading,stack,pthreads
When a thread exits, it's done. You can't "reuse" it - create another one. You can reuse your array of course - but not the values inside of it. (ie. need to pthread_create again) The question you cite was asking about the maximum number of /concurrent/ threads - OP was...
python,class,stack,queue,reverse
This will work. Your queue is composed of a list, so you can use slice syntax on the list to get a reversed version of the queue. class Queue: def __init__(self): self.items = [] def enqueue(self, item): self.items.append(item) def __str__(self): '''Allow print to be called on the queue object itself'''...
Actually it's what swap does, swaps program data and stack space: http://www.linuxjournal.com/article/10678 These are placed in anonymous pages, so named because they have no named filesystem source. Once modified, an anonymous page must remain in RAM for the duration of the program unless there is secondary storage to write it...