Page 1 of 2 12 Last
  • Jump to page:
    #1
  1. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Nov 2012
    Posts
    15
    Rep Power
    0

    Segmentation fault (core dumped) in this C code using pointer


    Hello everyeone!
    I am new to this forum , infact this is first time I am using forum for learning.
    I hope i will learn and share.

    I made this program and i am having a error " Segmentation fault (core dumped)".
    Can anyone please correct it.
    Thanks




    #include<stdio.h>
    # define x 10

    int main()
    {
    int ordr;
    int i, n;
    int *arr1, *arr2;
    int * array;
    //int *tab[20];
    //int * p;

    printf("\nEnter the order of table \n");
    scanf("%d" , &n);
    printf("\nEnter the first tableue\n");
    arr1 = inter(&n);
    printf("\nEnter the second table \n");
    arr2 = inter(&n);
    printf("\nThe first tablue is \n");
    affichage(arr1 ,n);
    printf("\nThe second tablue is \n");
    affichage(arr2 ,n);
    printf("\nThe multiplication of two table is \n");
    calcul(arr1, arr2, n);

    return 0;
    }
    int inter( int *n)
    {
    int *array;
    int p = *n;
    int i;
    array = (int *)malloc((*n)*sizeof(int));
    for (i = 0;i<p ; i++)
    {
    printf("Enter the value in array");
    scanf("%d",&array[i]);
    }
    return (array);
    }

    void affichage( int tab[] , int n)
    {

    int i;
    int *p;
    p = tab;

    for(i = 0 ;i<n; i++)
    {

    printf(" %d ", tab[i]);
    }
    }

    int calcul(int *a, int *b , int n)
    {
    int *c;
    int i;
    for(i = 0 ; i <n; i++)
    {
    c [i] = (a[i] * b[i]);
    }
    printf("\nThe result is \n");
    for (i =0 ; i <n ; i++)
    {
    printf("\t %d\n", c[i]);
    }
    }
  2. #2
  3. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Oct 2012
    Posts
    185
    Rep Power
    82
    Single step thru your code with a debugger and it will take you to the source of the problem.
  4. #3
  5. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Nov 2012
    Posts
    15
    Rep Power
    0
    sorry i cant understand?
    i am using linux and GCC compiler ?
    how to use debugger?
  6. #4
  7. Contributing User
    Devshed Supreme Being (6500+ posts)

    Join Date
    Jan 2003
    Location
    USA
    Posts
    7,086
    Rep Power
    2222
    To start off, please always use code tags. Failure to do so strips your code of all formatting and makes it unreadable. Here is what you posted with code tags. Please notice the difference.

    Code:
    #include<stdio.h>
    # define x 10
    
    int main()
    {
    	int ordr;
    	int i, n;
    	int *arr1, *arr2;
    	int * array;
    	//int *tab[20];  
    	//int * p;
    
    	printf("\nEnter the order of table \n");
    	scanf("%d" , &n);
    	printf("\nEnter the first tableue\n");
    	arr1 = inter(&n);
    	printf("\nEnter the second table \n");
    	arr2 = inter(&n);
    	printf("\nThe first tablue is \n");
    	affichage(arr1 ,n);
    	printf("\nThe second tablue is \n");
    	affichage(arr2 ,n);
    	printf("\nThe multiplication of two table is \n");
    	calcul(arr1, arr2, n);	
    
    return 0;
    }
    int inter( int *n)
    {
    	int *array;
    	int p = *n; 
    	int i;
    	array = (int *)malloc((*n)*sizeof(int));
    	for (i = 0;i<p ; i++)
    	{
    		printf("Enter the value in array");
    		scanf("%d",&array[i]);
    	}
    	return (array);
    }
    
    void affichage( int tab[] , int n)
    {
    
    	int i;
    	int *p;
    	p = tab;
    	
    	for(i = 0 ;i<n; i++)
    	{
    	
    		printf(" %d ", tab[i]);	
    	}
    }
    
    int calcul(int *a, int *b , int n)
    {
    	int *c;
    	int i;
    	for(i = 0 ; i <n; i++)
    	{
    		c [i] = (a[i] * b[i]);
    	}
    	printf("\nThe result is \n");
    	for (i =0 ; i <n ; i++)
    	{
    		printf("\t %d\n", c[i]);
    	}
    }
    BTW, decent job of indenting. Though setting your editor to replace tab characters with spaces would be a nice touch that would keep your code from being displayed with the default 8-column tab settings.

    Is this your real code or are you leaving anything out? Like the function prototypes. Here are the warnings I get without any corrections:
    C:>gcc -Wall p2.c
    p2.c:1: parse error before `{'
    p2.c:13: parse error before string constant
    p2.c:13: warning: type defaults to `int' in declaration of `printf'
    p2.c:13: warning: data definition has no type or storage class
    p2.c:14: parse error before string constant
    p2.c:14: warning: type defaults to `int' in declaration of `scanf'
    p2.c:14: warning: data definition has no type or storage class
    p2.c:15: parse error before string constant
    p2.c:15: warning: type defaults to `int' in declaration of `printf'
    p2.c:15: warning: data definition has no type or storage class
    p2.c:16: warning: type defaults to `int' in declaration of `arr1'
    p2.c:16: conflicting types for `arr1'
    p2.c:8: previous declaration of `arr1'
    p2.c:16: warning: implicit declaration of function `inter'
    p2.c:16: initializer element is not constant
    p2.c:16: warning: data definition has no type or storage class
    p2.c:17: parse error before string constant
    p2.c:17: warning: type defaults to `int' in declaration of `printf'
    p2.c:17: warning: data definition has no type or storage class
    p2.c:18: warning: type defaults to `int' in declaration of `arr2'
    p2.c:18: conflicting types for `arr2'
    p2.c:8: previous declaration of `arr2'
    p2.c:18: initializer element is not constant
    p2.c:18: warning: data definition has no type or storage class
    p2.c:19: parse error before string constant
    p2.c:19: warning: type defaults to `int' in declaration of `printf'
    p2.c:19: warning: data definition has no type or storage class
    p2.c:20: warning: type defaults to `int' in declaration of `affichage'
    p2.c:20: warning: parameter names (without types) in function declaration
    p2.c:20: warning: data definition has no type or storage class
    p2.c:21: parse error before string constant
    p2.c:21: warning: type defaults to `int' in declaration of `printf'
    p2.c:21: warning: data definition has no type or storage class
    p2.c:22: warning: type defaults to `int' in declaration of `affichage'
    p2.c:22: warning: parameter names (without types) in function declaration
    p2.c:22: warning: data definition has no type or storage class
    p2.c:23: parse error before string constant
    p2.c:23: warning: type defaults to `int' in declaration of `printf'
    p2.c:23: warning: data definition has no type or storage class
    p2.c:24: warning: type defaults to `int' in declaration of `calcul'
    p2.c:24: warning: parameter names (without types) in function declaration
    p2.c:24: warning: data definition has no type or storage class
    p2.c:26: parse error before `return'
    p2.c: In function `inter':
    p2.c:34: warning: implicit declaration of function `malloc'
    p2.c:40: warning: return makes integer from pointer without a cast
    p2.c: At top level:
    p2.c:44: conflicting types for `affichage'
    p2.c:22: previous declaration of `affichage'
    p2.c: In function `calcul':
    p2.c:70: warning: control reaches end of non-void function

    C:>
    Notice the warnings about default declarations and type conflicts when you "redeclare" those functions? That is why you use function prototypes to tell the compiler about the functions that you're going to be calling.

    Oh and also, are you making the mistake of ignoring warnings? Very stupid thing to do. Warnings are more important than error messages!

    Now that I've added function prototypes, here's what the compiler tells me:
    C:>gcc -Wall p2.c
    p2.c: In function `main':
    p2.c:20: warning: assignment makes pointer from integer without a cast
    p2.c:22: warning: assignment makes pointer from integer without a cast
    p2.c:13: warning: unused variable `array'
    p2.c:11: warning: unused variable `i'
    p2.c:10: warning: unused variable `ordr'
    p2.c: In function `inter':
    p2.c:38: warning: implicit declaration of function `malloc'
    p2.c:44: warning: return makes integer from pointer without a cast
    p2.c: In function `calcul':
    p2.c:74: warning: control reaches end of non-void function

    C:>
    See how much providing function prototypes cleaned up most of those warnings? OBTW, just what the hell were you thinking running a program with that many warnings? Warnings tell you that your code is confusing the compiler, so it has to make guesses about what you want it to do. A confused compiler can be a very dangerous beast. When you ran that program, you had no idea what it might do! Correct all warnings before even thinking about running the program!

    This is what's on line 20:
    arr1 = inter(&n);
    arr1 is declared as int*, but inter is declared as returning int. Not int*, which is what arr1 expects, but int. One's a pointer and the other's a value; two different things altogether.

    Also, you declare calcul as returning int, but then you don't return anything. When you make a promise to the compiler, then you keep that promise! Or else promise it what you're actually going to provide it.

    Clean up your code. Heed the warnings! Don't try to run it until it compiles clean with no warnings.

    Comments on this post

    • b49P23TIvg agrees : I apologize for admitting that that program could work with minor rearrangement.
  8. #5
  9. Contributing User
    Devshed Demi-God (4500 - 4999 posts)

    Join Date
    Aug 2011
    Posts
    4,696
    Rep Power
    480
    use emacs,
    load the c source into a buffer (new lines not shown)
    C-x C-f filename.c

    compile with
    M-x compile a=filename && touch $a.c && make -k CFLAGS='-O0 -g -Wall' $a

    run gdb with
    M-x gdb

    in gdb set break in main
    b main

    run the program
    r

    step through with
    s


    examine data with
    p cExpression


    That's how I do it.

    I reordered your program a little bit---you need to understand and repair warnings (I didn't). You should also verify that malloc succeeded. As for all the functions you call! The program worked for me.
    Code:
    #include<stdlib.h>
    #include<stdio.h>
    #define x 10
    
    void affichage( int tab[] , int n) {
      int i;
      int *p;
      p = tab;
      for(i = 0 ;i<n; i++)
        printf(" %d ", tab[i]);	
    }
    
    int calcul(int *a, int *b , int n) {
      int *c;
      int i;
      for(i = 0 ; i <n; i++)
        c [i] = (a[i] * b[i]);
      puts("\nThe result is");
      for (i =0 ; i <n ; i++)
        printf("\t %d\n", c[i]);
    }
    
    int inter( int *n) {
      int *array;
      int p = *n; 
      int i;
      array = (int *)malloc((*n)*sizeof(int));
      for (i = 0;i<p ; i++) {
        printf("Enter the value in array");
        scanf("%d",&array[i]);
      }
      return (array);
    }
    
    int main() {
      int ordr;
      int i, n;
      int *arr1, *arr2;
      int * array;
    
      printf("\nEnter the order of table \n");
      scanf("%d" , &n);
      printf("\nEnter the first tableue\n");
      arr1 = inter(&n);
      printf("\nEnter the second table \n");
      arr2 = inter(&n);
      printf("\nThe first tablue is \n");
      affichage(arr1 ,n);
      printf("\nThe second tablue is \n");
      affichage(arr2 ,n);
      printf("\nThe multiplication of two table is \n");
      calcul(arr1, arr2, n);	
    
      return 0;
    }
    
    
    
    #if 0
    -*- mode: compilation; default-directory: "/tmp/" -*-
    Compilation started at Sat Nov  3 18:43:33
    
    a=c && make -k $a
    cc -Wall -g -fpic -I/home/lambertdw/DWLinclude -L/home/lambertdw/DWLlib -L/usr/local/atlas/lib  c.c -ldwlhomoxform -ldwltool -lgsl -llapack -lptf77blas -lptcblas -latlas -lm -lncurses -lpthread  -o c
    c.c: In function ‘affichage’:
    c.c:7:8: warning: variable ‘p’ set but not used [-Wunused-but-set-variable]
    c.c: In function ‘inter’:
    c.c:32:3: warning: return makes integer from pointer without a cast [enabled by default]
    c.c: In function ‘main’:
    c.c:44:8: warning: assignment makes pointer from integer without a cast [enabled by default]
    c.c:46:8: warning: assignment makes pointer from integer without a cast [enabled by default]
    c.c:39:9: warning: unused variable ‘array’ [-Wunused-variable]
    c.c:37:7: warning: unused variable ‘i’ [-Wunused-variable]
    c.c:36:7: warning: unused variable ‘ordr’ [-Wunused-variable]
    c.c: In function ‘calcul’:
    c.c:21:1: warning: control reaches end of non-void function [-Wreturn-type]
    c.c:17:7: warning: ‘c’ may be used uninitialized in this function [-Wuninitialized]
    
    Compilation finished at Sat Nov  3 18:43:33
    
    
    
    
    
    
    ....gdb....
    
    
    
    
    
    
    Current directory is /tmp/
    GNU gdb (GDB) 7.5-ubuntu
    Copyright (C) 2012 Free Software Foundation, Inc.
    License GPLv3+: GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html>
    This is free software: you are free to change and redistribute it.
    There is NO WARRANTY, to the extent permitted by law.  Type "show copying"
    and "show warranty" for details.
    This GDB was configured as "x86_64-linux-gnu".
    For bug reporting instructions, please see:
    <http://www.gnu.org/software/gdb/bugs/>...
    Reading symbols from /tmp/c...done.
    (gdb) b main
    Breakpoint 1 at 0x4007b5: file c.c, line 41.
    (gdb) r
    Starting program: /tmp/c 
    
    Breakpoint 1, main () at c.c:41
    (gdb) continue
    Continuing.
    
    Enter the order of table 2
    
    
    Enter the first tableue
    Enter the value in array1
    Enter the value in array2
    
    Enter the second table 
    Enter the value in array3
    Enter the value in array4
    
    The first tablue is 
     1  2 
    The second tablue is 
     3  4 
    The multiplication of two table is 
    
    The result is
    	 3
    	 8
    [Inferior 1 (process 3235) exited normally]
    (gdb) quit
    
    Debugger finished
    #endif
    Last edited by b49P23TIvg; November 3rd, 2012 at 05:58 PM. Reason: fix it!
    [code]Code tags[/code] are essential for python code and Makefiles!
  10. #6
  11. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Nov 2012
    Posts
    15
    Rep Power
    0
    Thanks for the reply.
    I am new to programing and my concept are not good at all.
    SO i mixed up many things.
    I always use tab with my programing and intendations but here when i copied posted here i saw all things came like that.I thought maybe its forum it comes like this so i let it.
    And yes this was full program and I was neglecting the warnings as i was result oriented which i learn by you is a sign of bad programming.Actually i have to show this code so i was just focussing onthe output.

    I have to pass the "n" by call by reference to the function where i have to enter the value in array.

    I changed the code but still i m getting warnings

    Code:
    #include<stdio.h>
    
    int inter( int *n)
    {
    	int *array;
    	int p = *n; 
    	int i;
    	array = (int *)malloc((*n)*sizeof(int));
    	for (i = 0;i<p ; i++)
    	{
    		printf("Enter the value in array");
    		scanf("%d",&array[i]);
    	}
    	return (array);
    }
    
    void affichage( int tab[] , int n)
    {
    
    	int i;
    	for(i = 0 ;i<n; i++)
    		printf(" %d ", tab[i]);	
    }
    
    void calcul(int *a, int *b , int n)
    {
    	int *c=0;
    	int i;
    	for(i = 0 ; i <n; i++)
    		c  = (a[i] * b[i]);
    	printf("\nThe result is \n");
    	for (i =0 ; i <n ; i++)
    		printf("\t %d\n", c[i]);
    }
    
    
    int main()
    {
    	
    	int  n;
    	int *arr1, *arr2;
    	printf("\nEnter the order of table \n");
    	scanf("%d" , &n);
    	printf("\nEnter the first tableue\n");
    	arr1 = inter(&n);
    	printf("\nEnter the second table \n");
    	arr2 = inter(&n);
    	printf("\nThe first tablue is \n");
    	affichage(arr1 ,n);
    	printf("\nThe second tablue is \n");
    	affichage(arr2 ,n);
    	printf("\nThe multiplication of two table is \n");
    	calcul(arr1, arr2, n);	
    
    	return 0;
    }
    gcc -Wall p2.c
    p2.c: In function ‘inter’:
    p2.c:8:2: warning: implicit declaration of function ‘malloc’ [-Wimplicit-function-declaration]
    p2.c:8:17: warning: incompatible implicit declaration of built-in function ‘malloc’ [enabled by default]
    p2.c:14:2: warning: return makes integer from pointer without a cast [enabled by default]
    p2.c: In function ‘calcul’:
    p2.c:30:6: warning: assignment makes pointer from integer without a cast [enabled by default]
    p2.c: In function ‘main’:
    p2.c:45:7: warning: assignment makes pointer from integer without a cast [enabled by default]
    p2.c:47:7: warning: assignment makes pointer from integer without a cast [enabled by default]




    Can you please tell me how to remove this warnings specially the malloc one.
    How i handle this arr1 = inter(&n) ??
    should i return it like
    nt inter( int *n)
    {
    int *array;
    int p = *n;
    int i;
    array = (int *)malloc((*n)*sizeof(int));
    for (i = 0;i<p ; i++)
    {
    printf("Enter the value in array");
    scanf("%d",&array[i]);
    }
    return (*array);
    }


    Please do tell me and explain me this.

    Thanks.


    Originally Posted by dwise1_aol
    To start off, please always use code tags. Failure to do so strips your code of all formatting and makes it unreadable. Here is what you posted with code tags. Please notice the difference.

    Code:
    #include<stdio.h>
    # define x 10
    
    int main()
    {
    	int ordr;
    	int i, n;
    	int *arr1, *arr2;
    	int * array;
    	//int *tab[20];  
    	//int * p;
    
    	printf("\nEnter the order of table \n");
    	scanf("%d" , &n);
    	printf("\nEnter the first tableue\n");
    	arr1 = inter(&n);
    	printf("\nEnter the second table \n");
    	arr2 = inter(&n);
    	printf("\nThe first tablue is \n");
    	affichage(arr1 ,n);
    	printf("\nThe second tablue is \n");
    	affichage(arr2 ,n);
    	printf("\nThe multiplication of two table is \n");
    	calcul(arr1, arr2, n);	
    
    return 0;
    }
    int inter( int *n)
    {
    	int *array;
    	int p = *n; 
    	int i;
    	array = (int *)malloc((*n)*sizeof(int));
    	for (i = 0;i<p ; i++)
    	{
    		printf("Enter the value in array");
    		scanf("%d",&array[i]);
    	}
    	return (array);
    }
    
    void affichage( int tab[] , int n)
    {
    
    	int i;
    	int *p;
    	p = tab;
    	
    	for(i = 0 ;i<n; i++)
    	{
    	
    		printf(" %d ", tab[i]);	
    	}
    }
    
    int calcul(int *a, int *b , int n)
    {
    	int *c;
    	int i;
    	for(i = 0 ; i <n; i++)
    	{
    		c [i] = (a[i] * b[i]);
    	}
    	printf("\nThe result is \n");
    	for (i =0 ; i <n ; i++)
    	{
    		printf("\t %d\n", c[i]);
    	}
    }
    BTW, decent job of indenting. Though setting your editor to replace tab characters with spaces would be a nice touch that would keep your code from being displayed with the default 8-column tab settings.

    Is this your real code or are you leaving anything out? Like the function prototypes. Here are the warnings I get without any corrections:

    Notice the warnings about default declarations and type conflicts when you "redeclare" those functions? That is why you use function prototypes to tell the compiler about the functions that you're going to be calling.

    Oh and also, are you making the mistake of ignoring warnings? Very stupid thing to do. Warnings are more important than error messages!

    Now that I've added function prototypes, here's what the compiler tells me:

    See how much providing function prototypes cleaned up most of those warnings? OBTW, just what the hell were you thinking running a program with that many warnings? Warnings tell you that your code is confusing the compiler, so it has to make guesses about what you want it to do. A confused compiler can be a very dangerous beast. When you ran that program, you had no idea what it might do! Correct all warnings before even thinking about running the program!

    This is what's on line 20:
    arr1 = inter(&n);
    arr1 is declared as int*, but inter is declared as returning int. Not int*, which is what arr1 expects, but int. One's a pointer and the other's a value; two different things altogether.

    Also, you declare calcul as returning int, but then you don't return anything. When you make a promise to the compiler, then you keep that promise! Or else promise it what you're actually going to provide it.

    Clean up your code. Heed the warnings! Don't try to run it until it compiles clean with no warnings.
  12. #7
  13. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Nov 2012
    Posts
    15
    Rep Power
    0
    Thanks for your reply

    I checked your orginazations but it is not working with me.

    It has segemtation error in my pc.
    I do not know how it is working with yours.



    Originally Posted by b49P23TIvg
    use emacs,
    load the c source into a buffer (new lines not shown)
    C-x C-f filename.c

    compile with
    M-x compile a=filename && touch $a.c && make -k CFLAGS='-O0 -g -Wall' $a

    run gdb with
    M-x gdb

    in gdb set break in main
    b main

    run the program
    r

    step through with
    s


    examine data with
    p cExpression


    That's how I do it.

    I reordered your program a little bit---you need to understand and repair warnings (I didn't). You should also verify that malloc succeeded. As for all the functions you call! The program worked for me.
    Code:
    #include<stdlib.h>
    #include<stdio.h>
    #define x 10
    
    void affichage( int tab[] , int n) {
      int i;
      int *p;
      p = tab;
      for(i = 0 ;i<n; i++)
        printf(" %d ", tab[i]);	
    }
    
    int calcul(int *a, int *b , int n) {
      int *c;
      int i;
      for(i = 0 ; i <n; i++)
        c [i] = (a[i] * b[i]);
      puts("\nThe result is");
      for (i =0 ; i <n ; i++)
        printf("\t %d\n", c[i]);
    }
    
    int inter( int *n) {
      int *array;
      int p = *n; 
      int i;
      array = (int *)malloc((*n)*sizeof(int));
      for (i = 0;i<p ; i++) {
        printf("Enter the value in array");
        scanf("%d",&array[i]);
      }
      return (array);
    }
    
    int main() {
      int ordr;
      int i, n;
      int *arr1, *arr2;
      int * array;
    
      printf("\nEnter the order of table \n");
      scanf("%d" , &n);
      printf("\nEnter the first tableue\n");
      arr1 = inter(&n);
      printf("\nEnter the second table \n");
      arr2 = inter(&n);
      printf("\nThe first tablue is \n");
      affichage(arr1 ,n);
      printf("\nThe second tablue is \n");
      affichage(arr2 ,n);
      printf("\nThe multiplication of two table is \n");
      calcul(arr1, arr2, n);	
    
      return 0;
    }
    
    
    
    #if 0
    -*- mode: compilation; default-directory: "/tmp/" -*-
    Compilation started at Sat Nov  3 18:43:33
    
    a=c && make -k $a
    cc -Wall -g -fpic -I/home/lambertdw/DWLinclude -L/home/lambertdw/DWLlib -L/usr/local/atlas/lib  c.c -ldwlhomoxform -ldwltool -lgsl -llapack -lptf77blas -lptcblas -latlas -lm -lncurses -lpthread  -o c
    c.c: In function ‘affichage’:
    c.c:7:8: warning: variable ‘p’ set but not used [-Wunused-but-set-variable]
    c.c: In function ‘inter’:
    c.c:32:3: warning: return makes integer from pointer without a cast [enabled by default]
    c.c: In function ‘main’:
    c.c:44:8: warning: assignment makes pointer from integer without a cast [enabled by default]
    c.c:46:8: warning: assignment makes pointer from integer without a cast [enabled by default]
    c.c:39:9: warning: unused variable ‘array’ [-Wunused-variable]
    c.c:37:7: warning: unused variable ‘i’ [-Wunused-variable]
    c.c:36:7: warning: unused variable ‘ordr’ [-Wunused-variable]
    c.c: In function ‘calcul’:
    c.c:21:1: warning: control reaches end of non-void function [-Wreturn-type]
    c.c:17:7: warning: ‘c’ may be used uninitialized in this function [-Wuninitialized]
    
    Compilation finished at Sat Nov  3 18:43:33
    
    
    
    
    
    
    ....gdb....
    
    
    
    
    
    
    Current directory is /tmp/
    GNU gdb (GDB) 7.5-ubuntu
    Copyright (C) 2012 Free Software Foundation, Inc.
    License GPLv3+: GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html>
    This is free software: you are free to change and redistribute it.
    There is NO WARRANTY, to the extent permitted by law.  Type "show copying"
    and "show warranty" for details.
    This GDB was configured as "x86_64-linux-gnu".
    For bug reporting instructions, please see:
    <http://www.gnu.org/software/gdb/bugs/>...
    Reading symbols from /tmp/c...done.
    (gdb) b main
    Breakpoint 1 at 0x4007b5: file c.c, line 41.
    (gdb) r
    Starting program: /tmp/c 
    
    Breakpoint 1, main () at c.c:41
    (gdb) continue
    Continuing.
    
    Enter the order of table 2
    
    
    Enter the first tableue
    Enter the value in array1
    Enter the value in array2
    
    Enter the second table 
    Enter the value in array3
    Enter the value in array4
    
    The first tablue is 
     1  2 
    The second tablue is 
     3  4 
    The multiplication of two table is 
    
    The result is
    	 3
    	 8
    [Inferior 1 (process 3235) exited normally]
    (gdb) quit
    
    Debugger finished
    #endif
  14. #8
  15. Contributing User
    Devshed Supreme Being (6500+ posts)

    Join Date
    Jan 2003
    Location
    USA
    Posts
    7,086
    Rep Power
    2222
    Regarding malloc(). I noticed that you #include'd stdio.h. Why did you do that? Well, obviously because you want to use scanf and printf whose prototypes are in stdio.h, so you needed to #include stdio.h. Perfectly natural and logical. OK, you also want to use malloc, so shouldn't you also #include the header file that declares it? Would seem perfectly natural and logical. So which header file is that? Google'ing on man page malloc (or the same thing if your system has man pages or some other C help system installed), I found at the first of hits (emphasis via the color red added):
    malloc(3) - Linux man page
    Name

    malloc, free, calloc, realloc - Allocate and free dynamic memory
    Synopsis

    #include <stdlib.h>
    void *malloc(size_t size);void free(void *ptr);void *calloc(size_t nmemb,
    size_t size);void *realloc(void *ptr, size_t size);
    So to tell your compiler about malloc, you need to #include stdlib.h . Though stdlib.h also contains a number of other useful declarations, so I myself always #include it anyway for general purposes. Also, I had been raised on #including malloc.h for malloc, so call me "old fashioned".

    BTW, I explained it in this manner to take you through the thought process so that you will be able to think your way through it the next time. No insult was at all intended, but rather I wanted to make this a learning experience.

    Similarly, there's the problem of your inter() function. In main() where you assign its return value to arr1, arr1 is an int pointer which means that you need to assign an address (AKA a pointer value) to it. But you have declared inter() to return an integer value, not a pointer. The fault lies in your declaration of inter().

    Examine your inter() function:
    Code:
    int inter( int *n) {
      int *array;
      int p = *n; 
      int i;
      array = (int *)malloc((*n)*sizeof(int));
      for (i = 0;i<p ; i++) {
        printf("Enter the value in array");
        scanf("%d",&array[i]);
      }
      return (array);
    }
    What I see your intention as being here, you want inter() to create and fill an int array and return it to the calling function for it to use. You do this by passing in the number of integers that the array will contain, malloc space for that array keeping the address in the pointer variable array, then loop to have the user enter the values to go into it, then finally you return the array with return (array);. OK, so what did the compiler think of that return statement? This:
    p2.c:45: warning: return makes integer from pointer without a cast
    Why? Because array is a pointer, but you declared inter() to return an int. Not an int pointer, but rather a plain old int. And then when you call that function in main(), you try to assign that plain old int to an int pointer.

    Shouldn't you declare inter() to return an int pointer, since you want it to return the address of a int array and not just a single int value? That single asterix would clear up at least three warnings. Again, I walked you through the reasoning as a learning experience.

    And do start posting your code listings inside of code tags. Simply type [code] [/code] and then copy and paste your code listing between them. There's also some kind of button in the advanced editor, but I've never used that.
    Last edited by dwise1_aol; November 3rd, 2012 at 08:26 PM.
  16. #9
  17. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Nov 2012
    Posts
    15
    Rep Power
    0
    Thanks for the reply and I got where I was doing mistake.
    I really appreciate the way you told me, it was very helpful and nice way of explaining things.
    I am happy that I joined this forum where people are so helpful and they do not directly correct it but they explain us in an nice way and tell us to understand.

    This is a reall way of learning.
    Thanks a ton.

    I got your point so i changed my code in to this , but there is some problems in the function Calcul.

    Code:
    #include<stdio.h>
    #include<stdlib.h>
    int* inter( int *n)
    {
    	int *array;
    	int p = *n; 
    	int i;
    	array = (int *)malloc((*n)*sizeof(int));
    	for (i = 0;i<p ; i++)
    	{
    		printf("Enter the value in array");
    		scanf("%d",&array[i]);
    	}
    	return (array);
    }
    
    void affichage( int tab[] , int n)
    {
    
    	int i;
    	for(i = 0 ;i<n; i++)
    		printf(" %d ", tab[i]);	
    }
    
    void calcul(int *a, int *b , int n)
    {
    	int *c;
    	int i;
    	for(i = 0 ; i <n; i++)
    		c[i]  = (a[i] * b[i]);
    	printf("\nThe result is \n");
    	for (i =0 ; i <n ; i++)
    		printf("\t %d\n", c[i]);
    }
    
    int main()
    {
    	int  n;
    	int *arr1, *arr2;
    	printf("\nEnter the order of table \n");
    	scanf("%d" , &n);
    	printf("\nEnter the first tableue\n");
    	arr1 = inter(&n);
    	printf("\nEnter the second table \n");
    	arr2 = inter(&n);
    	printf("\nThe first tablue is \n");
    	affichage(arr1 ,n);
    	printf("\nThe second tablue is \n");
    	affichage(arr2 ,n);
    	printf("\nThe multiplication of two table is \n");
    	calcul(arr1, arr2, n);	
    	return 0;
    }

    gcc -Wall p2.c
    p2.c: In function ‘calcul’:
    p2.c:30:4: warning: ‘c’ may be used uninitialized in this function [-Wuninitialized]


    there is warning in calcul that c maybe used unintialised.
    If i put int *c = 0, there is no warning but there is segmentation error while calculating the multiplication.

    In output it is
    Segmentation fault (core dumped).

    One more thing how to set the number lines in GCC compiler and how to put it by default that when we press enter , the cursor comes after a space of tab itself.
  18. #10
  19. Contributed User
    Devshed Specialist (4000 - 4499 posts)

    Join Date
    Jun 2005
    Posts
    4,363
    Rep Power
    1870
    > If i put int *c = 0, there is no warning but there is segmentation error while calculating the multiplication.
    Look at your inter function.
    Why is it calling malloc?


    > One more thing how to set the number lines in GCC compiler and how to put it by default
    > that when we press enter , the cursor comes after a space of tab itself.
    Smart indentation is a feature of your editor / IDE, not your compiler. The compiler doesn't care whether you use notepad or visual studio to write the code, so long as it can save a text file.
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper
  20. #11
  21. Commie Mutant Traitor
    Devshed Intermediate (1500 - 1999 posts)

    Join Date
    Jun 2004
    Location
    Norcross, GA (again)
    Posts
    1,804
    Rep Power
    1569
    The reason for this is because c is an integer pointer, but you never set it to point to anything useful. In the original version, it was simply uninitialized, which means it had whatever garbage was in the memory address it's at; hence the waroning. The second attempt does initialize c, but to an address that is protected and outside of your ability to access it, hence the segfault.

    Since you do not know the size of the need array at compiler time, the solution is use calloc() to allocate an array for the computation. Given your current code, you would probably do something like this:
    Code:
    void calcul(int *a, int *b , int n)
    {
        int *c;
        int i;
    
        c = (int*) calloc(n, sizeof(int));
    
        for(i = 0 ; i <n; i++)
            c[i]  = (a[i] * b[i]);
            printf("\nThe result is \n");
            for (i =0 ; i <n ; i++)
                printf("\t %d\n", c[i]);
        
        /* remember to de-allocate the memory after you've finished with it */
        free(c);
    }
    However, as a matter of 'best practices', I would suggest separating the calculation from the I/O:

    Code:
    void calcul(int *a, int *b , int n)
    {
        int *c;
        int i;
    
        c = (int*) calloc(n, sizeof(int));
    
        for(i = 0 ; i <n; i++)
        {
            c[i]  = (a[i] * b[i]);
        }
    
        return c;
    }
    
    int main()
    {
        int  n;
        int *arr1, *arr2, *result;
        printf("\nEnter the order of table \n");
        scanf("%d" , &n);
    
        printf("\nEnter the first table\n");
        arr1 = inter(&n);
    
        printf("\nEnter the second table \n");
        arr2 = inter(&n);
    
        printf("\nThe first table is \n");
        affichage(arr1 ,n);
    
        printf("\nThe second table is \n");
        affichage(arr2 ,n);
    
        printf("\nThe result of multiplying the two tables is \n");
        result = calcul(arr1, arr2, n);
        affichage(result, n);
        /* always free allocated memory, even if you're at the end of the program */
        free(result);
        free(arr1);
        free(arr2);
    
        return 0;
    }
    Why separate them like this? Because it makes both parts more general, and because it conceptually separates the interface from the computation, making it easier to reason about hem individually.

    BTW, why are passing the size of the array to inter() as a pointer? Since you don't change n anywhere in the function, there is no need to pass it by reference.

    Finally, I would like to ask, what editor are you using? Most programmer's editors have an option to automagically use spaces instead of tabs when the TAB key is entered. While the choice of tabs vs. spaces is an old religious war, spaces have generally won in the current era, so it is usually better to replace tabs with spaces whenever possible (just remember to change that option when editing a Makefile).
    Rev First Speaker Schol-R-LEA;2 JAM LCF ELF KoR KCO BiWM TGIF
    #define KINSEY (rand() % 7) λ Scheme is the Red Pill
    Scheme in ShortUnderstanding the C/C++ Preprocessor
    Taming PythonA Highly Opinionated Review of Programming Languages for the Novice, v1.1

    FOR SALE: One ShapeSystem 2300 CMD, extensively modified for human use. Includes s/w for anthro, transgender, sex-appeal enhance, & Gillian Anderson and Jason D. Poit clone forms. Some wear. $4500 obo. tverres@et.ins.gov
  22. #12
  23. Contributing User
    Devshed Supreme Being (6500+ posts)

    Join Date
    Jan 2003
    Location
    USA
    Posts
    7,086
    Rep Power
    2222
    [I]gcc -Wall p2.c
    p2.c: In function ‘calcul’:
    p2.c:30:4: warning: ‘c’ may be used uninitialized in this function [-Wuninitialized]
    That is because the pointer c has not been initialized.

    I know that pointers must be an abstract concept for you, but for me when I first encountered them (in Pascal, but C was the same) they were very concrete. In our curriculum, first semester was FORTRAN but then the second semester was assembly language. Every computer has a Central Processing Unit (CPU) and every CPU has registers (for temporarily holding data it's working with and for special purposes such as arithmetic operations (the accumulator) and knowing the location of the next instruction (the instruction pointer) and holding the address of data (ie, a pointer) ) and a set of instructions, each of which perform a specific operation (eg, move data around between registers and memory locations, arithmetic and logical operations, comparison and testing, jumping to a new instruction location). Each CPU is different and has a different instruction set, though there are families of processors (eg, Intel's 80x86 family used in DOS/Windows and many Linux boxes) that reuse and expand upon the same instruction set. These instructions and their operands are all binary numbers, so the first translation programs were assemblers that translated human-readable lists of instructions to machine-readable instructions, one line of assembly code per machine instruction. High-level compilers that compile to native code all translate your source code in a higher-level language (eg, C) to the corresponding assembly code; most compilers have an option to print out that assembly code for you.

    The point is that I had already encountered the concept of pointers and how they work and had worked with them back in assembly, a few years before encountering them in a higher-level language (assembly in 1978, Pascal in 1980, C in 1990) -- PL/I offered the capabilities of pointers but not pointers themselves, similar to Java and C#. I also did a lot of low-level PC programming in the 1980's, so I understand almost instinctively what pointers do, how they do it, what kinds of memory locations they need to point to, what kinds of memory locations they must never point to, what happens when they try to access memory that they mustn't, and the simple fact that they always point somewhere even if you have never initialized them (ie, that is one gun that is always loaded; you can never safe that gun and must always handle it accordingly).

    You want c to point to an array, but you never create that array. You need to malloc that array into existence at the start of the function and even more importantly you must free() it at the end of the function since you will have no more need of it after returning from the function and because the pointer to that array will disappear at that time leaving you with no way to free that malloc'd memory at a later time. This gets us into the subject of dropped pointers and of memory leaks, which become vitally important when you start doing linked lists and in C++, where memory leaks become the most insidious of bugs.

    When you declare a local variable (ie, a non-static variable declared in a function), it's created in temporary storage reserved for that function on the stack. Those variables are all created when you call the function and they all go away when you leave the function -- remember that very well because it's a very important concept that you must never forget.

    The next important concept about functions and the stack is that the physical memory used by the stack gets reused over and over again. Actually, all memory location are the same way as the operating system and all the processes run, such that your new process is reusing memory locations that other processes had used previously. Corollary to this is what I said about memory location being like a gun that you can never empty: every memory location always have something loaded in it. That's in the nature of the electronics itself. So that means that when you call a function and before you assign your own values to them, the local variables contain whatever had last been written to that location by another function or process or whatever random sequence of bits just happened to appear when you powered up. The technical term for those "random" values is garbage.

    An uninitialized local variable contains garbage and an uninitialized pointer contains a garbage address. That means that an uninitialized pointer contains an address to you-have-no-idea-where, it could be pointing anywhere. If you're lucky, it will point outside of the memory space your process had been allocated (processes are given memory to use, called a "memory space", and may only access addresses within their own memory space; this is how the OS protects itself against you) and cause the OS to terminate your process with extreme prejudice due to a segfault. If you're unlucky, then you'll overwrite part of your own process (called "clobbering") causing any number of really bizarre bugs.

    When you set c to zero, you actually set it to memory location 0. In MS-DOS, that is where the system's Interrupt Vector Table (IVT) resided and, since I seem to recall that the processor itself requires that table to be at that location, I believe that Windows and Intel-based Linux continue to use that location as the IVT. That table contains the addresses of the OS code that handle real-world electronic and software events that trigger an interrupt; interrupt servicing is an extremely important aspect of processor and operating system operation. If you were to clobber any part of the IVT, you will cause the entire system to crash (an all too common occurrence with MS-DOS, which did not have memory protection and whose programming techniques included rewriting the IVT so that it would run your own interrupt service routines (ISRs) ). So when you tried to write to the IVT, the OS quite naturally protected itself from you.

    So now you know why using a garbage pointer or a NULL pointer will cause a segmentation fault (SEGFAULT) and cause your program to crash. And you know that what you need to do is to malloc that array, assigning its address to c (thus initializing the pointer), and that you also need to free() that array at the end of the function. Please also note that you do not free the arrays created by inter() because you have need for them after returning from that function, but rather you will free them at the end of the program itself (this is done automatically when your program terminates).

    One more thing how to set the number lines in GCC compiler and how to put it by default that when we press enter , the cursor comes after a space of tab itself.
    I do not understand what you are asking here. That sounds like a question about your editor, but we don't know what editor you're using. If it concerns how the display acts when the user is inputting the array values, then use printf to insert that tab.
  24. #13
  25. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Nov 2012
    Posts
    15
    Rep Power
    0
    Thanks for the reply and i learned lots of new things .

    I was not using free() because i was thinking that it will remove the value.
    for example , in the function if i used free(c) , it would remove the value which c contains, this was my misconception which is cleared now.

    And I why was passing the size of the array in the function because this is how the questions says to do.

    And i am using Gedit in linux and I really feels weird that I do not know how to set the automatically tab or space itself.I am sorry i am very new to linux and programming things.I am learning and will like to know as much as I could.

    Yes it made it easier to understand the program as u return the value to the main.

    The final code is under and this is perfectly working.

    Code:
    #include<stdio.h>
    #include<stdlib.h>
    int* inter( int *n)
    {
    	int *array;
    	int p = *n; 
    	int i;
    	array = (int *)malloc((*n)*sizeof(int));
    	for (i = 0;i<p ; i++)
    	{
    		printf("Enter the value in array");
    		scanf("%d",&array[i]);
    	}
    	return (array);
    }
    
    void affichage( int tab[] , int n)
    {
    
    	int i;
    	for(i = 0 ;i<n; i++)
    		printf(" %d ", tab[i]);	
    }
    
    int* calcul(int *a, int *b , int n)
    {
    	int *c;
    	int i;
    	c = (int *) calloc (n,sizeof(int));
    	for(i = 0 ; i <n; i++)
    		c[i]  = (a[i] * b[i]);
    	
    	return c;
    }
    
    int main()
    {
    	int  n;
    	int *arr1, *arr2 , *result;
    
    	printf("\nEnter the order of table \n");
    	scanf("%d" , &n);
    
    	printf("\nEnter the first tableue\n");
    	arr1 = inter(&n);
    
    	printf("\nEnter the second table \n");
    	arr2 = inter(&n);
    
    	printf("\nThe first tablue is \n");
    	affichage(arr1 ,n);
    
    	printf("\nThe second tablue is \n");
    	affichage(arr2 ,n);
    
    	printf("\nThe multiplication of two table is \n");
    	result = calcul(arr1, arr2, n);	
    
    	affichage(result, n);
    
    	free(arr1);
    	free(arr2);
    	free(result);
    	return 0;
    }

    Thanks everyone for helping me and teaching me.
  26. #14
  27. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Nov 2012
    Posts
    15
    Rep Power
    0
    thank you so much for elaborating the concept of malloc and free.It is so helpful and so full of informations.And i really like the examples and cpmparison you made with the other languages.
    It seems you are computer genius and i am very happy to be a part of this forum where people knows so clearly .

    you cleared my doubt of using free() which i just wrote to reply in last post.

    And i m using GEDITOR in linux and i am referring to this "though setting your editor to replace tab characters with spaces would be a nice touch that would keep your code from being displayed with the default 8-column tab settings".

    I was thinking that if it automatically takes a space of 8colun without pressing a tab button but i have to press tab button every time i start a new line.

    I got where it is in GEDITOR,

    Once again Thanks and sorry that I am new in this linux and languages programming.I have to learn C and JAVA in which i am very new.I hope I will learn alot here in this forum..





    Originally Posted by dwise1_aol
    That is because the pointer c has not been initialized.

    I know that pointers must be an abstract concept for you, but for me when I first encountered them (in Pascal, but C was the same) they were very concrete. In our curriculum, first semester was FORTRAN but then the second semester was assembly language. Every computer has a Central Processing Unit (CPU) and every CPU has registers (for temporarily holding data it's working with and for special purposes such as arithmetic operations (the accumulator) and knowing the location of the next instruction (the instruction pointer) and holding the address of data (ie, a pointer) ) and a set of instructions, each of which perform a specific operation (eg, move data around between registers and memory locations, arithmetic and logical operations, comparison and testing, jumping to a new instruction location). Each CPU is different and has a different instruction set, though there are families of processors (eg, Intel's 80x86 family used in DOS/Windows and many Linux boxes) that reuse and expand upon the same instruction set. These instructions and their operands are all binary numbers, so the first translation programs were assemblers that translated human-readable lists of instructions to machine-readable instructions, one line of assembly code per machine instruction. High-level compilers that compile to native code all translate your source code in a higher-level language (eg, C) to the corresponding assembly code; most compilers have an option to print out that assembly code for you.

    The point is that I had already encountered the concept of pointers and how they work and had worked with them back in assembly, a few years before encountering them in a higher-level language (assembly in 1978, Pascal in 1980, C in 1990) -- PL/I offered the capabilities of pointers but not pointers themselves, similar to Java and C#. I also did a lot of low-level PC programming in the 1980's, so I understand almost instinctively what pointers do, how they do it, what kinds of memory locations they need to point to, what kinds of memory locations they must never point to, what happens when they try to access memory that they mustn't, and the simple fact that they always point somewhere even if you have never initialized them (ie, that is one gun that is always loaded; you can never safe that gun and must always handle it accordingly).

    You want c to point to an array, but you never create that array. You need to malloc that array into existence at the start of the function and even more importantly you must free() it at the end of the function since you will have no more need of it after returning from the function and because the pointer to that array will disappear at that time leaving you with no way to free that malloc'd memory at a later time. This gets us into the subject of dropped pointers and of memory leaks, which become vitally important when you start doing linked lists and in C++, where memory leaks become the most insidious of bugs.

    When you declare a local variable (ie, a non-static variable declared in a function), it's created in temporary storage reserved for that function on the stack. Those variables are all created when you call the function and they all go away when you leave the function -- remember that very well because it's a very important concept that you must never forget.

    The next important concept about functions and the stack is that the physical memory used by the stack gets reused over and over again. Actually, all memory location are the same way as the operating system and all the processes run, such that your new process is reusing memory locations that other processes had used previously. Corollary to this is what I said about memory location being like a gun that you can never empty: every memory location always have something loaded in it. That's in the nature of the electronics itself. So that means that when you call a function and before you assign your own values to them, the local variables contain whatever had last been written to that location by another function or process or whatever random sequence of bits just happened to appear when you powered up. The technical term for those "random" values is garbage.

    An uninitialized local variable contains garbage and an uninitialized pointer contains a garbage address. That means that an uninitialized pointer contains an address to you-have-no-idea-where, it could be pointing anywhere. If you're lucky, it will point outside of the memory space your process had been allocated (processes are given memory to use, called a "memory space", and may only access addresses within their own memory space; this is how the OS protects itself against you) and cause the OS to terminate your process with extreme prejudice due to a segfault. If you're unlucky, then you'll overwrite part of your own process (called "clobbering") causing any number of really bizarre bugs.

    When you set c to zero, you actually set it to memory location 0. In MS-DOS, that is where the system's Interrupt Vector Table (IVT) resided and, since I seem to recall that the processor itself requires that table to be at that location, I believe that Windows and Intel-based Linux continue to use that location as the IVT. That table contains the addresses of the OS code that handle real-world electronic and software events that trigger an interrupt; interrupt servicing is an extremely important aspect of processor and operating system operation. If you were to clobber any part of the IVT, you will cause the entire system to crash (an all too common occurrence with MS-DOS, which did not have memory protection and whose programming techniques included rewriting the IVT so that it would run your own interrupt service routines (ISRs) ). So when you tried to write to the IVT, the OS quite naturally protected itself from you.

    So now you know why using a garbage pointer or a NULL pointer will cause a segmentation fault (SEGFAULT) and cause your program to crash. And you know that what you need to do is to malloc that array, assigning its address to c (thus initializing the pointer), and that you also need to free() that array at the end of the function. Please also note that you do not free the arrays created by inter() because you have need for them after returning from that function, but rather you will free them at the end of the program itself (this is done automatically when your program terminates).


    I do not understand what you are asking here. That sounds like a question about your editor, but we don't know what editor you're using. If it concerns how the display acts when the user is inputting the array values, then use printf to insert that tab.
  28. #15
  29. Contributing User
    Devshed Supreme Being (6500+ posts)

    Join Date
    Jan 2003
    Location
    USA
    Posts
    7,086
    Rep Power
    2222
    Originally Posted by srsiddiqui
    And i am using Gedit in linux and I really feels weird that I do not know how to set the automatically tab or space itself.I am sorry i am very new to linux and programming things.I am learning and will like to know as much as I could.
    In gedit main menu: Edit | Preferences (it's at the bottom). In the gedit Preferences dialog box that pops up, Editor tab. Tab stops is at the top of that property page with a check box for "Insert spaces instead of tabs".

    The handy thing about GUIs is that there's a more or less standard logic to the layout of the menus. From there, it's just a matter of searching through the menus following likely leads (eg, Preferences, Options) until you find what you are looking for. It might be well hidden (ie, not put where you would expect it) or not even available (GUIs are notorious for being arbitrary in what they allow you to do, what with the programmer not being able to anticipate all users' desires), but this is the approach to take.
Page 1 of 2 12 Last
  • Jump to page:

IMN logo majestic logo threadwatch logo seochat tools logo