簡體   English   中英

在C中使用線程將命令行中的字符串反轉-分段錯誤

[英]Reversing the strings from command line with threads in C - segmentation fault

我是線程新手。

我正在嘗試制作一個C程序,該程序反轉命令行中給出的字符串,並創建一個為每個線程執行此操作的線程。 當我運行它給我細分錯誤。

這是代碼:

 #include <stdio.h>
#include <sys/types.h>
#include <pthread.h>
#include <stdlib.h>
#include <fcntl.h>

char* final[1000];

pthread_mutex_t *mutex = PTHREAD_MUTEX_INITIALIZER;
pthread_t p[];

void *reverse(void* arg){
char* s[100];
char* temp;
int i;
strcpy(s,(char*)arg);
printf("S este %s",s);
for(i=0;i<=strlen(s)/2;i++){
    strcpy(temp,s[i]);
    strcpy(s[i],s[strlen(s)-i-1]);
    strcpy(s[strlen(s)-i-1],temp);
}

sleep(1);
pthread_mutex_lock(&mutex);
strcat(final,s);
printf("Intermediar %s",s);
pthread_mutex_unlock(&mutex);
return NULL;
} 



int main(int argc,char* argv[]) {
int i;
int n = argc;
strcpy(final,"");
for(i=1;i<n-2;i++){
    pthread_create(&p[i],NULL,reverse,argv[i]);
}
for(i=1;i<n-2;i++){
    pthread_join(p[i],NULL);
}
//printf("Sirul final este %s",final);
return 0;
 }

有誰知道一個好的網站可以幫助我學習線程?

謝謝 !

char* final[1000];

是一個指向char的指針數組(包含1000個元素),您需要一個char數組:

char final[1000];

這個數組有同樣的問題:

char* s[100];

temp被聲明為指針,但是您將其用作大小為1的數組

聲明不帶*的互斥量,刪除初始化並添加main:

pthread_mutex_init(&mutex, NULL);

您還應該在pthread_t的數組定義中添加一個數字

您永遠不會初始化temp ,因此調用strcpy(temp, s[i]); 導致未定義的行為。

您對s處理也很混亂,將arg (一個字符串)復制到s (一個字符串指針數組)使用的內存中是無效的。 僅僅因為您可以拋棄警告,並不意味着您在做明智的事情。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM