Programmer's Blog

Programmer's reference

Category Archives: C program

[gdb] Commands for examining program in assembly

i r
i all-r
i f
i proc m
disas 
x/4xw (10w) $sp
x/5i
x/i $pc
Advertisements

[C] Returnable 2D array and readfile

char** create2DCharArray(int m, int n)
{
   char* values = calloc(m*n, sizeof(char));
   char** rows = malloc(n*sizeof(char*));
   int i;
   for (i=0; i<n; ++i)
   {
       rows[i] = values + i*m;
   }
   return rows;
}

void destroy2DCharArray(char** arr)
{
   free(*arr);
   free(arr);
}

char** readFileInto2DArray ( const char* fileName )
{
   FILE *f;
   f = fopen(fileName,"r");
   char ch, strr[32767], *str;
   int row = 0, column = 0, i = 0, j = 0;
   while(fgets(strr, sizeof strr, f))
   {
      row++;
      if(column < strlen(strr) )
           column = strlen(strr);
   }
   rewind(f);
   char** arr = create2DCharArray(column,row);
   while(i < row)
   {
     do
     {
        ch = fgetc(f);
        if ( ch == '\r')
        ch = fgetc(f);
        arr[i][j] = ch;
        j++;
     }
     while( !( ch == '\n' || ch == EOF ) );
     arr[i][--j] = '\0';
     i++;
     j = 0;
   }
   fclose(f);
   return arr;
}

[C] Binary semaphore example

/*a synchronization example*/
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <string.h>
#include <pthread.h>
#include <semaphore.h>

void *thread_fnc(void * arg);

sem_t my_semaphore;
char my_string[100];

int main()
{
   int value;
   pthread_t my_thread;
   void *ret_join;

   if(sem_init(&my_semaphore, 0, 0)) {
     perror("semaphore init failed\n");
     exit(1);
   }

   if(pthread_create(&my_thread, NULL, thread_fnc, NULL)) {
     perror("pthread_create failed\n");
     exit(1);
   }

   while(strncmp("quit", my_string, 4) != 0) {
     fgets(my_string, 100, stdin);
     //sem_post will resume the thread which waiting at sem_wait()
     sem_post(&my_semaphore);
   }

   if(pthread_join(my_thread, &ret_join)) {
     perror("pthread_join failed");
     exit(1);
   }
   printf("Thread joined(%s\n)", (char *) ret_join);
   sem_destroy(&my_semaphore);
   exit(0);
}

void *thread_fnc(void *arg)
{
   int val;

   while(strncmp("quit", my_string, 4) != 0) {

   sem_wait(&my_semaphore);
   sscanf(my_string, "%d", &val);

   printf("%d \n",val);

   }
   pthread_exit(NULL);
}


result:
89   //input
89   //display from thread_fnc
2449
2449
...