linux下使用gdb調試崩潰丶死結執行個體__linux

來源:互聯網
上載者:User

gdb是linux下一款功能強大的調試工具,windows下對應的有windbg,下面舉例說明常見程式錯誤解決方案

1.gdb啟動

要想使用gdb調試,編譯時間指定-g選項加入調試資訊,gdb可以啟動執行檔案,attach正在運行程式,偵錯工具崩潰產生core檔案

啟動gdb後輸入run運行,continue繼續,quiet退出,下面是調試一段崩潰和死結的源碼

#include <pthread.h> #include <stdlib.h> #include <stdio.h> #include <unistd.h> #include <string.h> pthread_mutex_t mutex; int count = 0;void print_pid_tid() { pid_t   pid; pthread_t   tid; pid = getpid(); tid = pthread_self(); printf("pid %u tid %u (0x%x)\n", (unsigned int)pid, (unsigned int)tid, (unsigned int)tid); } void callback_func(){pthread_mutex_lock(&mutex); printf("count:%d\n",count);}void *thread_func1(void *arg) { while (1){int n = *((int *)arg);pthread_mutex_lock(&mutex); print_pid_tid(); count += 2;for (int i=0 ; i < 5; ++i ) {count += n;} callback_func();pthread_mutex_unlock(&mutex); sleep(1);}return 0;} void *thread_func2(void *arg){while (1){pthread_mutex_lock(&mutex); printf("thread_func2 run\n");pthread_mutex_unlock(&mutex); sleep(1);}return 0;}void *thread_func3(void *arg){while(1){char *str = NULL;//strcpy(str,"hello world");sleep(1);}return 0;}int main(void) { pthread_t ntid; int count = 10; pthread_mutex_init(&mutex, NULL); int err = pthread_create(&ntid, NULL, thread_func1, &count); if ( 0 != err ) { printf("pthread_create1:%s\n", strerror(err)); } err = pthread_create(&ntid, NULL, thread_func2, &count); if ( 0 != err ) { printf("pthread_create2:%s\n", strerror(err)); }err = pthread_create(&ntid, NULL, thread_func3, &count); if ( 0 != err ) { printf("pthread_create3:%s\n", strerror(err)); }getchar();int **ret = NULL; pthread_join(ntid, (void**)ret); printf("pthread_join:%p\n", *ret); pthread_mutex_destroy(&mutex); return 0; } 

2.調試崩潰

gdb綁定程式運行崩潰時,gdb會停留在程式最後運行棧位置,一般輸入bt查看堆棧,frame n切換棧幀,print列印是否null 指標導致崩潰,where查看對於源碼位置或者list列出原始碼,崩潰一般有null 指標,數組越界,記憶體非法訪問


3.調試死結

程式出現死結時會是卡死狀態,如果gdb綁定運行使用ctrl+c中斷程式,輸入info threads查看所有線程,使用thread n切換線程,線上程中輸入bt查看線程堆棧,定位程式停留位置,一般比較多個線程鎖或者是否有死迴圈



4.斷點調試

設定斷點,如b main.cpp:31,執行到斷點後next單步,step進入函數,continue繼續運行


聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.