Segmentation Fault(core dumped) pthread Announcing the arrival of Valued Associate #679: Cesar Manara Planned maintenance scheduled April 23, 2019 at 23:30 UTC (7:30 pm US/Eastern) Data science time! April 2019 and salary with experience The Ask Question Wizard is Live!Core dumped, but core file is not in the current directory?What is a segmentation fault?Pthread condition variable unpredictable outcomewhat is Segmentation fault (core dumped)?Segmentation fault (core dumped) and zlibpThreads Segmentation Faultphtread_kill() Segmentation fault (core dumped)pthread_create type error. What am i missing?pthread segmentation fault (core dumped) errorCode segmentation fault (core dumped) pthread creation

Was Objective-C really a hindrance to Apple software development?

Why do people think Winterfell crypts is the safest place for women, children & old people?

Writing a T-SQL stored procedure to receive 4 numbers and insert them into a table

Is Bran literally the world's memory?

Is there a way to fake a method response using Mock or Stubs?

What does the black goddess statue do and what is it?

What were wait-states, and why was it only an issue for PCs?

Israeli soda type drink

How to compute a Jacobian using polar coordinates?

What's parked in Mil Moscow helicopter plant?

/bin/ls sorts differently than just ls

What does こした mean?

Are these square matrices always diagonalisable?

Test if all elements of a Foldable are the same

What *exactly* is electrical current, voltage, and resistance?

My admission is revoked after accepting the admission offer

How was Lagrange appointed professor of mathematics so early?

Has a Nobel Peace laureate ever been accused of war crimes?

How would it unbalance gameplay to rule that Weapon Master allows for picking a fighting style?

How can I wire a 9-position switch so that each position turns on one more LED than the one before?

What is the purpose of the side handle on a hand ("eggbeater") drill?

Marquee sign letters

`FindRoot [ ]`::jsing: Encountered a singular Jacobian at a point...WHY

What is the numbering system used for the DSN dishes?



Segmentation Fault(core dumped) pthread



Announcing the arrival of Valued Associate #679: Cesar Manara
Planned maintenance scheduled April 23, 2019 at 23:30 UTC (7:30 pm US/Eastern)
Data science time! April 2019 and salary with experience
The Ask Question Wizard is Live!Core dumped, but core file is not in the current directory?What is a segmentation fault?Pthread condition variable unpredictable outcomewhat is Segmentation fault (core dumped)?Segmentation fault (core dumped) and zlibpThreads Segmentation Faultphtread_kill() Segmentation fault (core dumped)pthread_create type error. What am i missing?pthread segmentation fault (core dumped) errorCode segmentation fault (core dumped) pthread creation



.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty height:90px;width:728px;box-sizing:border-box;








1















I have this code but it has an error: Segmentation Fault(core dumped) and it doesn't work with more the 2 threads. Any idea of what am i doing wrong?



This code is for calculate pi by Leibniz formula



#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <malloc.h>


#define NUM_HILOS 2

struct datos

int inicio;
int fin;
float *pi;


*calcPi (void *datos)
struct datos *datos_proceso;
datos_proceso = (struct datos *) datos;
int i = datos_proceso -> inicio;
int end = datos_proceso -> fin;
printf("inicio %d n", i);
printf("fin %d n", end);
float *pi = datos_proceso -> pi;
int signo = 1;
do
*pi = *pi +(signo*4.0)/((2*i)+1);
i++;
signo *= -1;
//printf("%f n", *pi);
while(i<end);



int main()

int error, i;
float *pi;
int j = -1;
/*variable para hilos*/


I think that the error is over here but i don't know how to fix it



 struct datos hilo_datos[NUM_HILOS];
pthread_t idhilo[NUM_HILOS];
//printf("este es pi %f n", *pi);
for(i=0; i<NUM_HILOS; i++)

hilo_datos[i].inicio =j+1;
hilo_datos[i].fin =j+1000;
hilo_datos[i].pi = pi;
printf("%d n", hilo_datos[i].inicio);
printf("%d n", hilo_datos[i].fin);
j += 1000;


for(i=0; i<NUM_HILOS; i++)

error=pthread_create(&idhilo[i], NULL, (void *)calcPi, &hilo_datos[i]);




for(i=0; i<NUM_HILOS; i++)

pthread_join(idhilo[i], NULL);

printf("este es pi %f n", *pi);
return 0;










share|improve this question



















  • 2





    Have you tried using GDB to step through your code? I'm pretty sure Martin is right - hilo_datos is a pointer pointing to a memory space enough for only one datos struct. So hilo_datos[0] I think should work but you segfault at hilo_datos[1]. Maybe you wanted to malloc (sizeof (hilo_datos) * NUM_HILOS)?

    – Franco Solleza
    Nov 3 '15 at 1:08







  • 1





    Should you call malloc like this struct datos* hilo_datos = (struct datos*) malloc(NUM_HILOS * sizeof (struct datos));)?

    – Fiddling Bits
    Nov 3 '15 at 1:10







  • 1





    You should learn how to run a program in GDB (or another debugger). That should point you straight to where you're using hilo_datos[i].

    – roeland
    Nov 3 '15 at 1:26







  • 1





    hilo_datos[i].pi = pi;. pi is an uninitialised variable. That is, you have not allocated any memory for pi and then you dereference it within the thread code.

    – kaylum
    Nov 3 '15 at 2:24






  • 1





    Even if float *pi and the memory it pointed to were correctly initialized, it would still be undefined behavior due to unsynchronized writes to it in multiple threads.

    – EOF
    Nov 3 '15 at 12:29

















1















I have this code but it has an error: Segmentation Fault(core dumped) and it doesn't work with more the 2 threads. Any idea of what am i doing wrong?



This code is for calculate pi by Leibniz formula



#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <malloc.h>


#define NUM_HILOS 2

struct datos

int inicio;
int fin;
float *pi;


*calcPi (void *datos)
struct datos *datos_proceso;
datos_proceso = (struct datos *) datos;
int i = datos_proceso -> inicio;
int end = datos_proceso -> fin;
printf("inicio %d n", i);
printf("fin %d n", end);
float *pi = datos_proceso -> pi;
int signo = 1;
do
*pi = *pi +(signo*4.0)/((2*i)+1);
i++;
signo *= -1;
//printf("%f n", *pi);
while(i<end);



int main()

int error, i;
float *pi;
int j = -1;
/*variable para hilos*/


I think that the error is over here but i don't know how to fix it



 struct datos hilo_datos[NUM_HILOS];
pthread_t idhilo[NUM_HILOS];
//printf("este es pi %f n", *pi);
for(i=0; i<NUM_HILOS; i++)

hilo_datos[i].inicio =j+1;
hilo_datos[i].fin =j+1000;
hilo_datos[i].pi = pi;
printf("%d n", hilo_datos[i].inicio);
printf("%d n", hilo_datos[i].fin);
j += 1000;


for(i=0; i<NUM_HILOS; i++)

error=pthread_create(&idhilo[i], NULL, (void *)calcPi, &hilo_datos[i]);




for(i=0; i<NUM_HILOS; i++)

pthread_join(idhilo[i], NULL);

printf("este es pi %f n", *pi);
return 0;










share|improve this question



















  • 2





    Have you tried using GDB to step through your code? I'm pretty sure Martin is right - hilo_datos is a pointer pointing to a memory space enough for only one datos struct. So hilo_datos[0] I think should work but you segfault at hilo_datos[1]. Maybe you wanted to malloc (sizeof (hilo_datos) * NUM_HILOS)?

    – Franco Solleza
    Nov 3 '15 at 1:08







  • 1





    Should you call malloc like this struct datos* hilo_datos = (struct datos*) malloc(NUM_HILOS * sizeof (struct datos));)?

    – Fiddling Bits
    Nov 3 '15 at 1:10







  • 1





    You should learn how to run a program in GDB (or another debugger). That should point you straight to where you're using hilo_datos[i].

    – roeland
    Nov 3 '15 at 1:26







  • 1





    hilo_datos[i].pi = pi;. pi is an uninitialised variable. That is, you have not allocated any memory for pi and then you dereference it within the thread code.

    – kaylum
    Nov 3 '15 at 2:24






  • 1





    Even if float *pi and the memory it pointed to were correctly initialized, it would still be undefined behavior due to unsynchronized writes to it in multiple threads.

    – EOF
    Nov 3 '15 at 12:29













1












1








1








I have this code but it has an error: Segmentation Fault(core dumped) and it doesn't work with more the 2 threads. Any idea of what am i doing wrong?



This code is for calculate pi by Leibniz formula



#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <malloc.h>


#define NUM_HILOS 2

struct datos

int inicio;
int fin;
float *pi;


*calcPi (void *datos)
struct datos *datos_proceso;
datos_proceso = (struct datos *) datos;
int i = datos_proceso -> inicio;
int end = datos_proceso -> fin;
printf("inicio %d n", i);
printf("fin %d n", end);
float *pi = datos_proceso -> pi;
int signo = 1;
do
*pi = *pi +(signo*4.0)/((2*i)+1);
i++;
signo *= -1;
//printf("%f n", *pi);
while(i<end);



int main()

int error, i;
float *pi;
int j = -1;
/*variable para hilos*/


I think that the error is over here but i don't know how to fix it



 struct datos hilo_datos[NUM_HILOS];
pthread_t idhilo[NUM_HILOS];
//printf("este es pi %f n", *pi);
for(i=0; i<NUM_HILOS; i++)

hilo_datos[i].inicio =j+1;
hilo_datos[i].fin =j+1000;
hilo_datos[i].pi = pi;
printf("%d n", hilo_datos[i].inicio);
printf("%d n", hilo_datos[i].fin);
j += 1000;


for(i=0; i<NUM_HILOS; i++)

error=pthread_create(&idhilo[i], NULL, (void *)calcPi, &hilo_datos[i]);




for(i=0; i<NUM_HILOS; i++)

pthread_join(idhilo[i], NULL);

printf("este es pi %f n", *pi);
return 0;










share|improve this question
















I have this code but it has an error: Segmentation Fault(core dumped) and it doesn't work with more the 2 threads. Any idea of what am i doing wrong?



This code is for calculate pi by Leibniz formula



#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <malloc.h>


#define NUM_HILOS 2

struct datos

int inicio;
int fin;
float *pi;


*calcPi (void *datos)
struct datos *datos_proceso;
datos_proceso = (struct datos *) datos;
int i = datos_proceso -> inicio;
int end = datos_proceso -> fin;
printf("inicio %d n", i);
printf("fin %d n", end);
float *pi = datos_proceso -> pi;
int signo = 1;
do
*pi = *pi +(signo*4.0)/((2*i)+1);
i++;
signo *= -1;
//printf("%f n", *pi);
while(i<end);



int main()

int error, i;
float *pi;
int j = -1;
/*variable para hilos*/


I think that the error is over here but i don't know how to fix it



 struct datos hilo_datos[NUM_HILOS];
pthread_t idhilo[NUM_HILOS];
//printf("este es pi %f n", *pi);
for(i=0; i<NUM_HILOS; i++)

hilo_datos[i].inicio =j+1;
hilo_datos[i].fin =j+1000;
hilo_datos[i].pi = pi;
printf("%d n", hilo_datos[i].inicio);
printf("%d n", hilo_datos[i].fin);
j += 1000;


for(i=0; i<NUM_HILOS; i++)

error=pthread_create(&idhilo[i], NULL, (void *)calcPi, &hilo_datos[i]);




for(i=0; i<NUM_HILOS; i++)

pthread_join(idhilo[i], NULL);

printf("este es pi %f n", *pi);
return 0;







c pthreads malloc






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Nov 3 '15 at 1:35







Arturo Ramírez

















asked Nov 3 '15 at 0:57









Arturo RamírezArturo Ramírez

93




93







  • 2





    Have you tried using GDB to step through your code? I'm pretty sure Martin is right - hilo_datos is a pointer pointing to a memory space enough for only one datos struct. So hilo_datos[0] I think should work but you segfault at hilo_datos[1]. Maybe you wanted to malloc (sizeof (hilo_datos) * NUM_HILOS)?

    – Franco Solleza
    Nov 3 '15 at 1:08







  • 1





    Should you call malloc like this struct datos* hilo_datos = (struct datos*) malloc(NUM_HILOS * sizeof (struct datos));)?

    – Fiddling Bits
    Nov 3 '15 at 1:10







  • 1





    You should learn how to run a program in GDB (or another debugger). That should point you straight to where you're using hilo_datos[i].

    – roeland
    Nov 3 '15 at 1:26







  • 1





    hilo_datos[i].pi = pi;. pi is an uninitialised variable. That is, you have not allocated any memory for pi and then you dereference it within the thread code.

    – kaylum
    Nov 3 '15 at 2:24






  • 1





    Even if float *pi and the memory it pointed to were correctly initialized, it would still be undefined behavior due to unsynchronized writes to it in multiple threads.

    – EOF
    Nov 3 '15 at 12:29












  • 2





    Have you tried using GDB to step through your code? I'm pretty sure Martin is right - hilo_datos is a pointer pointing to a memory space enough for only one datos struct. So hilo_datos[0] I think should work but you segfault at hilo_datos[1]. Maybe you wanted to malloc (sizeof (hilo_datos) * NUM_HILOS)?

    – Franco Solleza
    Nov 3 '15 at 1:08







  • 1





    Should you call malloc like this struct datos* hilo_datos = (struct datos*) malloc(NUM_HILOS * sizeof (struct datos));)?

    – Fiddling Bits
    Nov 3 '15 at 1:10







  • 1





    You should learn how to run a program in GDB (or another debugger). That should point you straight to where you're using hilo_datos[i].

    – roeland
    Nov 3 '15 at 1:26







  • 1





    hilo_datos[i].pi = pi;. pi is an uninitialised variable. That is, you have not allocated any memory for pi and then you dereference it within the thread code.

    – kaylum
    Nov 3 '15 at 2:24






  • 1





    Even if float *pi and the memory it pointed to were correctly initialized, it would still be undefined behavior due to unsynchronized writes to it in multiple threads.

    – EOF
    Nov 3 '15 at 12:29







2




2





Have you tried using GDB to step through your code? I'm pretty sure Martin is right - hilo_datos is a pointer pointing to a memory space enough for only one datos struct. So hilo_datos[0] I think should work but you segfault at hilo_datos[1]. Maybe you wanted to malloc (sizeof (hilo_datos) * NUM_HILOS)?

– Franco Solleza
Nov 3 '15 at 1:08






Have you tried using GDB to step through your code? I'm pretty sure Martin is right - hilo_datos is a pointer pointing to a memory space enough for only one datos struct. So hilo_datos[0] I think should work but you segfault at hilo_datos[1]. Maybe you wanted to malloc (sizeof (hilo_datos) * NUM_HILOS)?

– Franco Solleza
Nov 3 '15 at 1:08





1




1





Should you call malloc like this struct datos* hilo_datos = (struct datos*) malloc(NUM_HILOS * sizeof (struct datos));)?

– Fiddling Bits
Nov 3 '15 at 1:10






Should you call malloc like this struct datos* hilo_datos = (struct datos*) malloc(NUM_HILOS * sizeof (struct datos));)?

– Fiddling Bits
Nov 3 '15 at 1:10





1




1





You should learn how to run a program in GDB (or another debugger). That should point you straight to where you're using hilo_datos[i].

– roeland
Nov 3 '15 at 1:26






You should learn how to run a program in GDB (or another debugger). That should point you straight to where you're using hilo_datos[i].

– roeland
Nov 3 '15 at 1:26





1




1





hilo_datos[i].pi = pi;. pi is an uninitialised variable. That is, you have not allocated any memory for pi and then you dereference it within the thread code.

– kaylum
Nov 3 '15 at 2:24





hilo_datos[i].pi = pi;. pi is an uninitialised variable. That is, you have not allocated any memory for pi and then you dereference it within the thread code.

– kaylum
Nov 3 '15 at 2:24




1




1





Even if float *pi and the memory it pointed to were correctly initialized, it would still be undefined behavior due to unsynchronized writes to it in multiple threads.

– EOF
Nov 3 '15 at 12:29





Even if float *pi and the memory it pointed to were correctly initialized, it would still be undefined behavior due to unsynchronized writes to it in multiple threads.

– EOF
Nov 3 '15 at 12:29












1 Answer
1






active

oldest

votes


















1














Your errors were mainly forgetting simple things like variable initialization. When a pointer such as float *pi; is accessed before being initialized it will almost always cause problems. At the very least it should have raised a compiler warning. By the way, turn on all your compiler warnings. GCC options



Here are a few specifics to get a clean build...



1 add return statement to calcPi function



 ...
return 0;
}


2 terminate struct datos with a ;



struct datos 
...
;
^


3 function:



* calcPi (void *datos)...


should be:



void * calcPi (void *datos)...


Or better:



void calcPi (struct datos *d)... //passing a struct pointer 


4 Initialize your variables before using them. for example:



float *pi; //uninitialized
float *pi = NULL;//initialized pointer
pi = malloc(sizeof(float)*NUM_HILOS);//array of pi with NUM_HILOS elements


then, in following assignment statements use pi[i], ...



hilo_datos[i].pi = pi[i];


Or, just create a simple float: (you do not need a pointer in this case)



float pi = 0;//works just fine for what you are doing
//no further initialization is needed


Other problems include mis-application of threads, creating inappropriate variable types (i.e. for the way you are using it, float *pi; could just be float pi; negating the need for malloc())



A very simple example of using this algorithm to compute pi (without threading) is included below for illustration:



#include <stdio.h>
#include <stdlib.h>

#define NUM_HILOS 10 //array elements (no threads)

struct datos //modified for use as array, no threads

float pi; //PI
;

void calcPi (struct datos *d)

struct datos *datos_proceso = d;
float pi = datos_proceso[0].pi;
int signo = 1;
int i;

for(i=0;i<NUM_HILOS;i++)

pi = pi + (signo*4.0)/((2*i)+1);
signo *= -1;
d[i].pi = pi; //change values for NUM_HILOS to see how
//values for pi converge here.



int main()

int error, i;
float pi = 0;
int j = -1;

//your comment: I think that the error...
//... (The error you were seeing here was
//caused by an uninitialized float *pi; which has been
//changed to float pi = 0; in this example)

struct datos hilo_datos[NUM_HILOS];
for(i=0; i<NUM_HILOS; i++)

hilo_datos[i].pi = 0; //initialize all to zero


calcPi(hilo_datos);//send array of struct, check all elelments when returned

for(i=0; i<NUM_HILOS; i++)

printf("este es pi %f n", hilo_datos[i].pi);

getchar();
return 0;






share|improve this answer

























    Your Answer






    StackExchange.ifUsing("editor", function ()
    StackExchange.using("externalEditor", function ()
    StackExchange.using("snippets", function ()
    StackExchange.snippets.init();
    );
    );
    , "code-snippets");

    StackExchange.ready(function()
    var channelOptions =
    tags: "".split(" "),
    id: "1"
    ;
    initTagRenderer("".split(" "), "".split(" "), channelOptions);

    StackExchange.using("externalEditor", function()
    // Have to fire editor after snippets, if snippets enabled
    if (StackExchange.settings.snippets.snippetsEnabled)
    StackExchange.using("snippets", function()
    createEditor();
    );

    else
    createEditor();

    );

    function createEditor()
    StackExchange.prepareEditor(
    heartbeatType: 'answer',
    autoActivateHeartbeat: false,
    convertImagesToLinks: true,
    noModals: true,
    showLowRepImageUploadWarning: true,
    reputationToPostImages: 10,
    bindNavPrevention: true,
    postfix: "",
    imageUploader:
    brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
    contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
    allowUrls: true
    ,
    onDemand: true,
    discardSelector: ".discard-answer"
    ,immediatelyShowMarkdownHelp:true
    );



    );













    draft saved

    draft discarded


















    StackExchange.ready(
    function ()
    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f33489725%2fsegmentation-faultcore-dumped-pthread%23new-answer', 'question_page');

    );

    Post as a guest















    Required, but never shown

























    1 Answer
    1






    active

    oldest

    votes








    1 Answer
    1






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes









    1














    Your errors were mainly forgetting simple things like variable initialization. When a pointer such as float *pi; is accessed before being initialized it will almost always cause problems. At the very least it should have raised a compiler warning. By the way, turn on all your compiler warnings. GCC options



    Here are a few specifics to get a clean build...



    1 add return statement to calcPi function



     ...
    return 0;
    }


    2 terminate struct datos with a ;



    struct datos 
    ...
    ;
    ^


    3 function:



    * calcPi (void *datos)...


    should be:



    void * calcPi (void *datos)...


    Or better:



    void calcPi (struct datos *d)... //passing a struct pointer 


    4 Initialize your variables before using them. for example:



    float *pi; //uninitialized
    float *pi = NULL;//initialized pointer
    pi = malloc(sizeof(float)*NUM_HILOS);//array of pi with NUM_HILOS elements


    then, in following assignment statements use pi[i], ...



    hilo_datos[i].pi = pi[i];


    Or, just create a simple float: (you do not need a pointer in this case)



    float pi = 0;//works just fine for what you are doing
    //no further initialization is needed


    Other problems include mis-application of threads, creating inappropriate variable types (i.e. for the way you are using it, float *pi; could just be float pi; negating the need for malloc())



    A very simple example of using this algorithm to compute pi (without threading) is included below for illustration:



    #include <stdio.h>
    #include <stdlib.h>

    #define NUM_HILOS 10 //array elements (no threads)

    struct datos //modified for use as array, no threads

    float pi; //PI
    ;

    void calcPi (struct datos *d)

    struct datos *datos_proceso = d;
    float pi = datos_proceso[0].pi;
    int signo = 1;
    int i;

    for(i=0;i<NUM_HILOS;i++)

    pi = pi + (signo*4.0)/((2*i)+1);
    signo *= -1;
    d[i].pi = pi; //change values for NUM_HILOS to see how
    //values for pi converge here.



    int main()

    int error, i;
    float pi = 0;
    int j = -1;

    //your comment: I think that the error...
    //... (The error you were seeing here was
    //caused by an uninitialized float *pi; which has been
    //changed to float pi = 0; in this example)

    struct datos hilo_datos[NUM_HILOS];
    for(i=0; i<NUM_HILOS; i++)

    hilo_datos[i].pi = 0; //initialize all to zero


    calcPi(hilo_datos);//send array of struct, check all elelments when returned

    for(i=0; i<NUM_HILOS; i++)

    printf("este es pi %f n", hilo_datos[i].pi);

    getchar();
    return 0;






    share|improve this answer





























      1














      Your errors were mainly forgetting simple things like variable initialization. When a pointer such as float *pi; is accessed before being initialized it will almost always cause problems. At the very least it should have raised a compiler warning. By the way, turn on all your compiler warnings. GCC options



      Here are a few specifics to get a clean build...



      1 add return statement to calcPi function



       ...
      return 0;
      }


      2 terminate struct datos with a ;



      struct datos 
      ...
      ;
      ^


      3 function:



      * calcPi (void *datos)...


      should be:



      void * calcPi (void *datos)...


      Or better:



      void calcPi (struct datos *d)... //passing a struct pointer 


      4 Initialize your variables before using them. for example:



      float *pi; //uninitialized
      float *pi = NULL;//initialized pointer
      pi = malloc(sizeof(float)*NUM_HILOS);//array of pi with NUM_HILOS elements


      then, in following assignment statements use pi[i], ...



      hilo_datos[i].pi = pi[i];


      Or, just create a simple float: (you do not need a pointer in this case)



      float pi = 0;//works just fine for what you are doing
      //no further initialization is needed


      Other problems include mis-application of threads, creating inappropriate variable types (i.e. for the way you are using it, float *pi; could just be float pi; negating the need for malloc())



      A very simple example of using this algorithm to compute pi (without threading) is included below for illustration:



      #include <stdio.h>
      #include <stdlib.h>

      #define NUM_HILOS 10 //array elements (no threads)

      struct datos //modified for use as array, no threads

      float pi; //PI
      ;

      void calcPi (struct datos *d)

      struct datos *datos_proceso = d;
      float pi = datos_proceso[0].pi;
      int signo = 1;
      int i;

      for(i=0;i<NUM_HILOS;i++)

      pi = pi + (signo*4.0)/((2*i)+1);
      signo *= -1;
      d[i].pi = pi; //change values for NUM_HILOS to see how
      //values for pi converge here.



      int main()

      int error, i;
      float pi = 0;
      int j = -1;

      //your comment: I think that the error...
      //... (The error you were seeing here was
      //caused by an uninitialized float *pi; which has been
      //changed to float pi = 0; in this example)

      struct datos hilo_datos[NUM_HILOS];
      for(i=0; i<NUM_HILOS; i++)

      hilo_datos[i].pi = 0; //initialize all to zero


      calcPi(hilo_datos);//send array of struct, check all elelments when returned

      for(i=0; i<NUM_HILOS; i++)

      printf("este es pi %f n", hilo_datos[i].pi);

      getchar();
      return 0;






      share|improve this answer



























        1












        1








        1







        Your errors were mainly forgetting simple things like variable initialization. When a pointer such as float *pi; is accessed before being initialized it will almost always cause problems. At the very least it should have raised a compiler warning. By the way, turn on all your compiler warnings. GCC options



        Here are a few specifics to get a clean build...



        1 add return statement to calcPi function



         ...
        return 0;
        }


        2 terminate struct datos with a ;



        struct datos 
        ...
        ;
        ^


        3 function:



        * calcPi (void *datos)...


        should be:



        void * calcPi (void *datos)...


        Or better:



        void calcPi (struct datos *d)... //passing a struct pointer 


        4 Initialize your variables before using them. for example:



        float *pi; //uninitialized
        float *pi = NULL;//initialized pointer
        pi = malloc(sizeof(float)*NUM_HILOS);//array of pi with NUM_HILOS elements


        then, in following assignment statements use pi[i], ...



        hilo_datos[i].pi = pi[i];


        Or, just create a simple float: (you do not need a pointer in this case)



        float pi = 0;//works just fine for what you are doing
        //no further initialization is needed


        Other problems include mis-application of threads, creating inappropriate variable types (i.e. for the way you are using it, float *pi; could just be float pi; negating the need for malloc())



        A very simple example of using this algorithm to compute pi (without threading) is included below for illustration:



        #include <stdio.h>
        #include <stdlib.h>

        #define NUM_HILOS 10 //array elements (no threads)

        struct datos //modified for use as array, no threads

        float pi; //PI
        ;

        void calcPi (struct datos *d)

        struct datos *datos_proceso = d;
        float pi = datos_proceso[0].pi;
        int signo = 1;
        int i;

        for(i=0;i<NUM_HILOS;i++)

        pi = pi + (signo*4.0)/((2*i)+1);
        signo *= -1;
        d[i].pi = pi; //change values for NUM_HILOS to see how
        //values for pi converge here.



        int main()

        int error, i;
        float pi = 0;
        int j = -1;

        //your comment: I think that the error...
        //... (The error you were seeing here was
        //caused by an uninitialized float *pi; which has been
        //changed to float pi = 0; in this example)

        struct datos hilo_datos[NUM_HILOS];
        for(i=0; i<NUM_HILOS; i++)

        hilo_datos[i].pi = 0; //initialize all to zero


        calcPi(hilo_datos);//send array of struct, check all elelments when returned

        for(i=0; i<NUM_HILOS; i++)

        printf("este es pi %f n", hilo_datos[i].pi);

        getchar();
        return 0;






        share|improve this answer















        Your errors were mainly forgetting simple things like variable initialization. When a pointer such as float *pi; is accessed before being initialized it will almost always cause problems. At the very least it should have raised a compiler warning. By the way, turn on all your compiler warnings. GCC options



        Here are a few specifics to get a clean build...



        1 add return statement to calcPi function



         ...
        return 0;
        }


        2 terminate struct datos with a ;



        struct datos 
        ...
        ;
        ^


        3 function:



        * calcPi (void *datos)...


        should be:



        void * calcPi (void *datos)...


        Or better:



        void calcPi (struct datos *d)... //passing a struct pointer 


        4 Initialize your variables before using them. for example:



        float *pi; //uninitialized
        float *pi = NULL;//initialized pointer
        pi = malloc(sizeof(float)*NUM_HILOS);//array of pi with NUM_HILOS elements


        then, in following assignment statements use pi[i], ...



        hilo_datos[i].pi = pi[i];


        Or, just create a simple float: (you do not need a pointer in this case)



        float pi = 0;//works just fine for what you are doing
        //no further initialization is needed


        Other problems include mis-application of threads, creating inappropriate variable types (i.e. for the way you are using it, float *pi; could just be float pi; negating the need for malloc())



        A very simple example of using this algorithm to compute pi (without threading) is included below for illustration:



        #include <stdio.h>
        #include <stdlib.h>

        #define NUM_HILOS 10 //array elements (no threads)

        struct datos //modified for use as array, no threads

        float pi; //PI
        ;

        void calcPi (struct datos *d)

        struct datos *datos_proceso = d;
        float pi = datos_proceso[0].pi;
        int signo = 1;
        int i;

        for(i=0;i<NUM_HILOS;i++)

        pi = pi + (signo*4.0)/((2*i)+1);
        signo *= -1;
        d[i].pi = pi; //change values for NUM_HILOS to see how
        //values for pi converge here.



        int main()

        int error, i;
        float pi = 0;
        int j = -1;

        //your comment: I think that the error...
        //... (The error you were seeing here was
        //caused by an uninitialized float *pi; which has been
        //changed to float pi = 0; in this example)

        struct datos hilo_datos[NUM_HILOS];
        for(i=0; i<NUM_HILOS; i++)

        hilo_datos[i].pi = 0; //initialize all to zero


        calcPi(hilo_datos);//send array of struct, check all elelments when returned

        for(i=0; i<NUM_HILOS; i++)

        printf("este es pi %f n", hilo_datos[i].pi);

        getchar();
        return 0;







        share|improve this answer














        share|improve this answer



        share|improve this answer








        edited Mar 9 at 4:13

























        answered Nov 6 '15 at 21:04









        ryykerryyker

        12.7k22959




        12.7k22959





























            draft saved

            draft discarded
















































            Thanks for contributing an answer to Stack Overflow!


            • Please be sure to answer the question. Provide details and share your research!

            But avoid


            • Asking for help, clarification, or responding to other answers.

            • Making statements based on opinion; back them up with references or personal experience.

            To learn more, see our tips on writing great answers.




            draft saved


            draft discarded














            StackExchange.ready(
            function ()
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f33489725%2fsegmentation-faultcore-dumped-pthread%23new-answer', 'question_page');

            );

            Post as a guest















            Required, but never shown





















































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown

































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown







            Popular posts from this blog

            Save data to MySQL database using ExtJS and PHP [closed]2019 Community Moderator ElectionHow can I prevent SQL injection in PHP?Which MySQL data type to use for storing boolean valuesPHP: Delete an element from an arrayHow do I connect to a MySQL Database in Python?Should I use the datetime or timestamp data type in MySQL?How to get a list of MySQL user accountsHow Do You Parse and Process HTML/XML in PHP?Reference — What does this symbol mean in PHP?How does PHP 'foreach' actually work?Why shouldn't I use mysql_* functions in PHP?

            Compiling GNU Global with universal-ctags support Announcing the arrival of Valued Associate #679: Cesar Manara Planned maintenance scheduled April 23, 2019 at 23:30 UTC (7:30pm US/Eastern) Data science time! April 2019 and salary with experience The Ask Question Wizard is Live!Tags for Emacs: Relationship between etags, ebrowse, cscope, GNU Global and exuberant ctagsVim and Ctags tips and trickscscope or ctags why choose one over the other?scons and ctagsctags cannot open option file “.ctags”Adding tag scopes in universal-ctagsShould I use Universal-ctags?Universal ctags on WindowsHow do I install GNU Global with universal ctags support using Homebrew?Universal ctags with emacsHow to highlight ctags generated by Universal Ctags in Vim?

            Add ONERROR event to image from jsp tldHow to add an image to a JPanel?Saving image from PHP URLHTML img scalingCheck if an image is loaded (no errors) with jQueryHow to force an <img> to take up width, even if the image is not loadedHow do I populate hidden form field with a value set in Spring ControllerStyling Raw elements Generated from JSP tagds with Jquery MobileLimit resizing of images with explicitly set width and height attributeserror TLD use in a jsp fileJsp tld files cannot be resolved