struct Stack* create(int max) {
struct Stack *stack = (struct Stack*)malloc(sizeof(struct Stack));
stack->maxSize = max;
stack->top = -1;
stack->array = (int*)malloc(stack->maxSize * sizeof(int));
return stack; }
int isFull(struct Stack* stack)
{
if(stack->top == stack->maxSize - 1)
{
printf("STACKOVERFLOW\n");
}
return stack->top == stack->maxSize - 1;
}
What is the use of struct Stack* stack in this question?
I am trying to understand stack but can't understand why dow we have to use this struct Stack* stack
The code is dynamically allocating the internal array that it is (presumably*) using as a stack. This keeps the implementer from having to predefine one or more fixed length arrays which would be wasteful. The use of a dynamically allocated data structure makes the code flexible. Presumably this is straight C code and the implementation of the code as a struct gives you advantages approaching that of an actual object in an actual object oriented language (partial [but not real] data hiding for example).
*I have to say presumably because the code is nor implementing any definite stack operations aside from checking if the stack is full (isFull() ).
Related
As far as I understand, in multithreaded environment reference counting should be performed with locking to ensure all threads see the same snapshot of memory. But locking slows down perfomance. How does Vala solve this problem?
Reference counting is mostly handled in GObject (for GLib.Object-derived types), which in turn uses the Atomic Operations in GLib. Atomics are a tricky subject; if you want to get into details a good place to start is Herb Sutter's Atomic Weapons talk from a few years ago. I would recommend watching the videos even if you're never going to put them to use (and 99.9% of programmers should never put them to use) because it will give you a much better understanding of how computers really work.
The name "atomics" can be a bit misleading; it's not really about atomicicity, though that's part of it. The operations are atomic in the sense that the change is either made in its entirety or not at all, which is vital, but the more interesting part is that atomics act as barriers which prevent the compiler from re-ordering operations across the barrier. Herb Sutter's talk goes into a lot of detail about this which I'm not going to repeat here.
For example, think about a simple unprotected reference counter:
typedef struct {
int reference_count = 0;
} Foo;
Foo* foo_create(void) {
Foo* foo = malloc(sizeof(Foo));
foo->reference_count = 1;
}
void ref(Foo* foo) {
++(foo->reference_count);
}
void unref(Foo* foo) {
if (--(foo->reference_count) == 0) {
free(foo);
}
}
I'm going to assume you can see the problems with leaving this unprotected because I'm writing a SO post not a book.
The specific atomic operation we're interested in is compare-and-swap (CAS), which basically provides the ability to perform this operation safely:
bool cas(int* value, int* expected, int desired) {
if (*value == *expected) {
*value = desired;
return true;
} else {
return false;
}
}
Using this, we would change our refcounting implementation above to something like:
typedef struct {
int reference_count = 0;
} Foo;
Foo* foo_create(void) {
Foo* foo = malloc(sizeof(Foo));
/* No atomics needed, we haven't made the value public yet */
foo->reference_count = 1;
}
void ref(Foo* foo) {
int old_refcount;
int new_refcount;
do {
current_refcount = foo->reference_count;
new_refcount = current_refcount + 1;
} while (!cas (&(foo->reference_count), &old_refcount, new_refcount))
}
void unref(Foo* foo) {
int old_refcount;
int new_refcount;
do {
current_refcount = foo->reference_count;
new_refcount = current_refcount - 1;
} while (!cas (&(foo->reference_count), &old_refcount, new_refcount));
if (new_refcount == 0) {
free(foo);
} else if (new_recount < 0) {
// Double-free bug, code should not be reached!
}
}
But locking slows down perfomance.
So do atomics. A lot. But also a lot less than a higher-level lock would. For one thing, if you were working with a mutex what you are doing would basically be:
Acquire the lock.
Perform the operation.
Release the lock.
With atomics, we're basically begging forgiveness instead of asking permission:
Attempt to perform the operation.
Then we just look to see whether the operation was successful (i.e., if cas() returned true).
The operation is also a lot smaller and faster; with a mutext, you would probably acquire the lock then read the current value, increment / decrement it, then release the lock. With atomics, the CAS operation gets wrapped up in a single CPU instruction.
The CPU still has to deal with cache coherency by making sure that next time any other core (a bit oversimplified since even within a core there are multiple caches) asks to read the data they are presented with the new data. In other words, atomic reference counting is bad for performance, but it's a lot less bad than a mutex. Frankly, if you want reference counting instead of tracing garbage collection atomics are pretty much your least-bad option.
Just did a standard job interview is to calculate the volume of water in the histogram. On Monday this code worked, and still works on this site. After updating vala, an error is now displayed.
UPD: more easy example
> Algoritm.vala:2.5-2.16: error: struct `Algotitm.first' cannot be empty
> struct first {
> ^^^^^^^^^^^^ Algoritm.vala:6.5-6.17: error: struct `Algotitm.second' cannot be empty
> struct second {
When posting a question on Stack Overflow it is always good to post an example of the code that is a minimum, complete and verifiable example.
From the link you've provided it appears you have a struct with only members marked as static:
struct First {
static int data;
static int pos;
}
void main () {
}
Marking the fields as static means they aren't instance fields and so the struct is empty of fields. That's why you are getting the error message about the struct being empty. I'm not sure Vala should even allow marking struct fields as static, but it does make sense to allow methods in structs to be static.
You need to remove the static modifiers. This will work:
struct First {
int data;
int pos;
}
void main () {
}
Update
I'm guessing you are trying to write performance optimized code and you think static helps with that. static in Vala means there is no instance data to use. If you are using a data structure like a class or struct then it only makes sense to have instances of those. If you want something to remain unchanged during the running of your program use const in a namespace.
Using a struct may give you a slight performance boost if your are using a very large number in your program. structs created in Vala are allocated on the stack instead of the heap so may be slightly faster. If you are passing structs around you may want to consider [SimpleType] attribute. That means structs will be passed by value in C as well as Vala. Without the [SimpleType] they are copied and passed by reference at the C level, which appears as copy by value in Vala.
Structs in Vala can have initializers (similar to a constructor for a class) and methods. So what I can extract from your second pastebin you could write that as:
struct First {
int data;
int pos;
public First (int[] mass) {
data= 5;
pos = mass.length;
}
public int sas () {
return data + pos;
}
}
void main () {
int[] a = {1,3,0,1,2,3,2,1};
var b = First (a);
print (#"$(b.sas ())\n");
}
That is a follow on question though and should be asked as a second question on Stack Overflow. This is a public forum that follows a format that allows other people to learn from the question and answers.
If I have access to an objective-C Protocol and trying to figure out how to look inside it to see what methods it contains, including their signatures, etc.
I've tried NSLog and looking in the object in the debugger, as well as on the internet, and cannot find any way to do this.
I checked out the methods in objc/runtime.h after seeing the answers to this SO post: List selectors for Objective-C object and found a way to NSLog a protocol's method signatures
#import <objc/runtime.h>
Protocol *protocol = #protocol(UITableViewDelegate);
BOOL showRequiredMethods = NO;
BOOL showInstanceMethods = YES;
unsigned int methodCount = 0;
struct objc_method_description *methods = protocol_copyMethodDescriptionList(protocol, showrequiredMethods, showInstanceMethods, &methodCount);
NSLog(#"%d required instance methods found:", methodCount);
for (int i = 0; i < methodCount; i++)
{
struct objc_method_description methodDescription = methods[i];
NSLog(#"Method #%d: %#", i, NSStringFromSelector(methodDescription.name));
}
free(methods)
The only catch is that in protocol_copyMethodDescriptionList you need to specify whether you want required vs. non-required methods and whether you want class vs. instance methods. So to cover all four cases, you would need to call protocol_copyMethodDescriptionList four times and print the results for each list.
I'm really unsure about handling tables in the C API of Lua.
The interface I'm currently developing requires me to read
contents of a table given to my c function:
example.lua:
myVector2 = {["x"]=20, ["y"]=30}
setSomePosition(myVector2)
C function I register as "setSomePosition":
static int lSetSomePosition(lua_State *L)
{
//number of arguments
if(lua_gettop(L) != 1)
{
//error handling
return 0;
}
//Need your help with the following:
//extract tables values of indexes "x" and "y"
return 0;
}
I know there are a couple of ways handling tables of which you sometimes need to know the indexes which I do. I'm just confused right now about this and the more I research the more I get confused. Probably because I don't really know how to describe what I'm after in proper terminology.
Would really appreciate some good commented example code of how you would fill in the gap in my c function :)
(If you've got an easy to understand guide to this topic don't mind commenting)
lua_getfield(L, 1, "x") //pushes a value of t["x"] onto the stack
lua_tonumber(L, -1) //returns the value at the top of the stack
lua_getfield(L, 1, "y") //pushes a value of t["y"] onto the stack
lua_tonumber(L, -1) //returns the value at the top of the stack
I am working on a chess engine in C/Objective-C and I rewrote a large part of my engine in straight-c to improve the speed. My question is, I have about 3KB of tables I initialize in my C file that I don't want to reinitialize every time a function from this file is called. If this were a regular objective-c class I would create a shared instance. However, the core of my engine is in two .h and a .c files. Should I make all of the tables used by my engine static? Will they persist between multiple other files calling functions in my engine? Should I make a static struct to hold my tables? I'm not sure what the best approach is here. Thanks!
Example:
Test.h:
int getInt(int index);
Test.c:
static int integers[4] = {1,2,3,4};
int getInt(int index) { return integers[index]; }
Every time I call getInt from another file, will it reallocate 'integers'? Or will it reuse the same array? I want to prevent it from unnecessarily reallocating a bunch of static arrays.
Ok, what you did was accessor on a static variable...
A static is only initialized once, so it does get initialized only once per launch.
You can keep it this way, or change it to a global to access it without calling function.
This code could typically get inlined, so changing it to a global is more a matter of taste than performances.
Edit: short summary on allocations
static int array[] = {1, 2}; // Allocated and initialized once
int array2[] = {1, 2, 3}; // Allocated and initialized once
int function() {
int array3[] = {1, 2, 3}; // Allocated and initialized at every call of function();
static int *array4 = malloc(42); // Allocated and initialized once
int *toto = malloc(42); // Allocated at every call of function();
}