Showing posts with label C-Programming. Show all posts
Showing posts with label C-Programming. Show all posts

Wednesday, January 8, 2014

Link List - C implementation

#include
#include

struct node {
  int value;
struct node *next;
};

void add_to_tail(struct node **head, int value)
{
  struct node *temp, *i;

  temp = malloc(sizeof(struct node));
  temp->value = value;
  temp->next = NULL;

    /* list empty */
  if (*head == NULL) {
*head = temp;
return;
}

/* find the tail node */
for( i = *head ; i->next != NULL ; i = i->next);

i->next = temp;
}

void print_list(struct node *head)
{
  struct node *i = head;

  while (i != NULL) {
printf("%d\n", i->value);
i = i->next;
}
}

void reverse_list(struct node **head)
{
struct node *prev, *curr, *next;

prev = NULL;
curr = *head;

while (curr != NULL) {
next = curr->next;
curr->next = prev;
prev = curr;
curr = next;
}

*head = prev;
}

int main(void)
{
struct node *head = NULL;

add_to_tail(&head, 1);
add_to_tail(&head, 2);
add_to_tail(&head, 3);
add_to_tail(&head, 4);

print_list(head);

reverse_list(&head);

print_list(head);
}

Wednesday, December 5, 2012

Volatile in simple terms


Consider this eg:

1  int main(void){
2  int a, x, y;
3  x=a;
4  y=a;
5  }

Line 3 with be converted to a LDR instruction.
Line 4 is where the compiler optimization comes in. It may be loaded from the previous loaded register.

Line 3: ldr r0[r1];   r1 is having the address of a
Line 4: mov r2 r0;   because we have value of a already in r0.

But if a is a volatile vairable, then compiler places ldr for both instructions( for x=a and y=a)
So Line 4 will change as follows,

Line 3: ldr r0[r1];   r1 is having the address of a
Line 4: ldr r2[r1];   r1 is having the address of a 

But if cache is enabled for these memory region, with the first ldr, data is cached. Now second ldr can fetch the data from cache. So using just volatile is not sufficient. Proper MMU mappings(non cached mapping in this case) is a must.