Sponsored Content
Full Discussion: why segment fault,
Top Forums Programming why segment fault, Post 302570613 by yanglei_fage on Thursday 3rd of November 2011 10:03:31 PM
Old 11-03-2011
why segment fault,

I always get segment fault, why? can sb help me and modify it, I have spend on much time on


Code:
#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/time.h>
#include <string.h>
#define MAX 10
pthread_t thread[2];

void *thread1()
{

    int *a[16];
    int i, n;


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

    n=(size_t) ((rand() * 256.0) / (RAND_MAX + 1.0)) + 1;
        a[i] = (int*)malloc(n);
    if (a[i]==NULL)
        {
            printf("Error allocating memory!");
            exit (1);
        }

       printf("malloc a[%d]\n",i);

    }

    for (i = 16; i > 0; i--)
    {

        n=(size_t) ((rand() * 256.0) / (RAND_MAX + 1.0)) + 1;
        printf("remalloc a[%d]\n",i-1);
        a[i - 1] = (int*)realloc(a[i - 1], n);
    if ( a[i - 1]==NULL)
        {
            printf("Error reallocating memory!");
            exit (1);
        }


    }
    for (i = 0; i < 16; i += 2 )
        free(a[i]);
        printf("free1 a[%d]\n",i);
    for (i = 16; i > 0; i -= 2)
        free(a[i - 1]);
        printf("free2 a[%d]\n",i-1);
        pthread_exit(NULL);
}


void thread_create(void)
{
        int temp,i;
        memset(&thread, 0, sizeof(thread));          //comment1
        /**/
       for (i = 2; i > 0; i--)
{
        if((temp = pthread_create(&thread[i], NULL, thread1, NULL)) != 0)       //comment2
                printf("thread create failed\n");
        else
                printf("thread create\n");
}
}

void thread_wait(void)
{
   int i;
   for (i = 2; i > 0; i--)
{
        if(thread[i] !=0) {                   //comment4
                pthread_join(thread[i],NULL);
                printf("1\n");
        }
}
}

int main()
{

        printf("\n");
        thread_create();
        printf("\n");
        thread_wait();

        return 0;
}


Last edited by yanglei_fage; 11-04-2011 at 12:04 AM..
 

10 More Discussions You Might Find Interesting

1. Programming

Segment Fault

When run it, segment fault. What is wrong? #include <stdio.h> #include <stdlib.h> const int max =20; //**************************************************** // Input Matrix //**************************************************** void inMatrixAA(int *AA, int row, int col)... (9 Replies)
Discussion started by: zhshqzyc
9 Replies

2. Shell Programming and Scripting

extract segment

Hey all, could someone please direct me on how to extract a segment from a file between two tags? Thanks! (1 Reply)
Discussion started by: mpang_
1 Replies

3. Programming

a strange segment fault about ltp-posix test

Hi all In the ltp-posix test,there is a case in open_posix_testsuite\conformance\interfaces\timer_gettime\speculative/6-1.c I run the above code,it will has a segment fault, if I modify it to below,it works well Anybody can tell me why? (1 Reply)
Discussion started by: yanglei_fage
1 Replies

4. Programming

How can I know where the segment of memory is all Zero?

I mean, I malloc a segment of memory, maybe 1k maybe 20bytes.. assume the pointer is pMem How can I know the content pMem refered is all Zero or \0 . I know memcmp but the second parameter should another memory address... thanx (4 Replies)
Discussion started by: macroideal
4 Replies

5. Programming

Segment Violation

Hi to all. I'm reciving a "Segment violation" error from this code and I don't know why. void insertAtEnd(NodeType *pList) { char element; printf("Introduce a element: \n"); setbuf(stdin, NULL); scanf("%c", &element); //Find the end of the list; while... (4 Replies)
Discussion started by: daniel.gbaena
4 Replies

6. Programming

Data segment or Text segment

Hi, Whether the following piece of code is placed in the read-only memory of code (text) segment or data segment? char *a = "Hello"; I am getting two different answers while searching in google :( that's why the confusion is (7 Replies)
Discussion started by: royalibrahim
7 Replies

7. Programming

Segment-fault handling for pthreads

Hi I have struggling a week to fix a program , in the begining i got SIGBUS , but after many attempts still the program gets SIGSEGV segment fault , In bellow i post the seg fault log + source codes. would really appreciate if experts help me to fix this segment fault error. any advice is... (2 Replies)
Discussion started by: pooyair
2 Replies

8. Programming

Using gdb, ignore beginning segmentation fault until reproduce environment segmentation fault

I use a binary name (ie polo) it gets some parameter , so for debugging normally i do this : i wrote script for watchdog my app (polo) and check every second if it's not running then start it , the problem is , if my app , remain in state of segmentation fault for a while (ie 15 ... (6 Replies)
Discussion started by: pooyair
6 Replies

9. Programming

Segment fault for C++ program when return vector

I am trying to reverse complement DNA sequence (string) with a short c++ code using boost library. Code was compiled without any warning/error, but ran into Segmentation fault. My guess is the function to return a vector, but not sure. #include <iostream> #include <fstream> #include <string>... (14 Replies)
Discussion started by: yifangt
14 Replies

10. Programming

Segment fault related to strlen.S

Hello, This function was copied into my code, which was compiled without error/warning, but when executed there is always Segmentation fault at the end after the output (which seems correct!): void get_hashes(unsigned int hash, unsigned char *in) { unsigned char *str = in; int pos =... (7 Replies)
Discussion started by: yifangt
7 Replies
PTHREAD_CANCEL(3)					     Linux Programmer's Manual						 PTHREAD_CANCEL(3)

NAME
pthread_cancel - send a cancellation request to a thread SYNOPSIS
#include <pthread.h> int pthread_cancel(pthread_t thread); Compile and link with -pthread. DESCRIPTION
The pthread_cancel() function sends a cancellation request to the thread thread. Whether and when the target thread reacts to the cancel- lation request depends on two attributes that are under the control of that thread: its cancelability state and type. A thread's cancelability state, determined by pthread_setcancelstate(3), can be enabled (the default for new threads) or disabled. If a thread has disabled cancellation, then a cancellation request remains queued until the thread enables cancellation. If a thread has enabled cancellation, then its cancelability type determines when cancellation occurs. A thread's cancellation type, determined by pthread_setcanceltype(3), may be either asynchronous or deferred (the default for new threads). Asynchronous cancelability means that the thread can be canceled at any time (usually immediately, but the system does not guarantee this). Deferred cancelability means that cancellation will be delayed until the thread next calls a function that is a cancellation point. A list of functions that are or may be cancellation points is provided in pthreads(7). When a cancellation requested is acted on, the following steps occur for thread (in this order): 1. Cancellation clean-up handlers are popped (in the reverse of the order in which they were pushed) and called. (See pthread_cleanup_push(3).) 2. Thread-specific data destructors are called, in an unspecified order. (See pthread_key_create(3).) 3. The thread is terminated. (See pthread_exit(3).) The above steps happen asynchronously with respect to the pthread_cancel() call; the return status of pthread_cancel() merely informs the caller whether the cancellation request was successfully queued. After a canceled thread has terminated, a join with that thread using pthread_join(3) obtains PTHREAD_CANCELED as the thread's exit status. (Joining with a thread is the only way to know that cancellation has completed.) RETURN VALUE
On success, pthread_cancel() returns 0; on error, it returns a nonzero error number. ERRORS
ESRCH No thread with the ID thread could be found. ATTRIBUTES
For an explanation of the terms used in this section, see attributes(7). +-----------------+---------------+---------+ |Interface | Attribute | Value | +-----------------+---------------+---------+ |pthread_cancel() | Thread safety | MT-Safe | +-----------------+---------------+---------+ CONFORMING TO
POSIX.1-2001, POSIX.1-2008. NOTES
On Linux, cancellation is implemented using signals. Under the NPTL threading implementation, the first real-time signal (i.e., signal 32) is used for this purpose. On LinuxThreads, the second real-time signal is used, if real-time signals are available, otherwise SIGUSR2 is used. EXAMPLE
The program below creates a thread and then cancels it. The main thread joins with the canceled thread to check that its exit status was PTHREAD_CANCELED. The following shell session shows what happens when we run the program: $ ./a.out thread_func(): started; cancellation disabled main(): sending cancellation request thread_func(): about to enable cancellation main(): thread was canceled Program source #include <pthread.h> #include <stdio.h> #include <errno.h> #include <stdlib.h> #include <unistd.h> #define handle_error_en(en, msg) do { errno = en; perror(msg); exit(EXIT_FAILURE); } while(0) static void * thread_func(void *ignored_argument) { int s; /* Disable cancellation for a while, so that we don't immediately react to a cancellation request */ s = pthread_setcancelstate(PTHREAD_CANCEL_DISABLE, NULL); if (s != 0) handle_error_en(s, "pthread_setcancelstate"); printf("thread_func(): started; cancellation disabled "); sleep(5); printf("thread_func(): about to enable cancellation "); s = pthread_setcancelstate(PTHREAD_CANCEL_ENABLE, NULL); if (s != 0) handle_error_en(s, "pthread_setcancelstate"); /* sleep() is a cancellation point */ sleep(1000); /* Should get canceled while we sleep */ /* Should never get here */ printf("thread_func(): not canceled! "); return NULL; } int main(void) { pthread_t thr; void *res; int s; /* Start a thread and then send it a cancellation request */ s = pthread_create(&thr, NULL, &thread_func, NULL); if (s != 0) handle_error_en(s, "pthread_create"); sleep(2); /* Give thread a chance to get started */ printf("main(): sending cancellation request "); s = pthread_cancel(thr); if (s != 0) handle_error_en(s, "pthread_cancel"); /* Join with thread to see what its exit status was */ s = pthread_join(thr, &res); if (s != 0) handle_error_en(s, "pthread_join"); if (res == PTHREAD_CANCELED) printf("main(): thread was canceled "); else printf("main(): thread wasn't canceled (shouldn't happen!) "); exit(EXIT_SUCCESS); } SEE ALSO
pthread_cleanup_push(3), pthread_create(3), pthread_exit(3), pthread_join(3), pthread_key_create(3), pthread_setcancelstate(3), pthread_setcanceltype(3), pthread_testcancel(3), pthreads(7) COLOPHON
This page is part of release 4.15 of the Linux man-pages project. A description of the project, information about reporting bugs, and the latest version of this page, can be found at https://www.kernel.org/doc/man-pages/. Linux 2017-09-15 PTHREAD_CANCEL(3)
All times are GMT -4. The time now is 10:33 PM.
Unix & Linux Forums Content Copyright 1993-2022. All Rights Reserved.
Privacy Policy