2017-02-25 51 views
-4

即時通訊初學者,我的英語不太好所以先抱歉。我寫了一個函數,它獲取一個字符串和一個數字,然後移動字符串'數字'步驟中的每個字母。我試圖調試它,它停止工作。誰知道這個問題?char arr =「...」;在C程序導致崩潰

這裏是我的代碼:

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

void moveString(char* str, int _switch); 

void main() 
{ 
    char arr = "abcdef"; 
    moveString(arr, 2); 
    printf("%s", arr); 
} 

void moveString(char* str, int _switch) 
{ 
    int len = strlen(str) + 1, i = 0, j = 0, move = len - _switch + 1; 
    char* temp = (char*)malloc(sizeof(char)*len); 
    if (!temp) 
     return NULL; 
    for (i = 0;i < move;i++) 
     temp[i+_switch] = str[i]; 
    for (j = 0;j < _switch;j++) 
     temp[j] = str[len - _switch + j + 1]; 
    str = temp; 
} 

這裏是錯誤:

Exception thrown at 0x0FCA1FD0 (ucrtbased char arr = ".dll) in ConsoleApplication3.exe: 0xC0000005: Access violation reading location 0x00000030."

+1

這甚至不應該編譯。你在聲明爲返回void的函數中返回NULL。 – melpomene

+1

你正在寫'temp [i + _switch]'。 'i'的值最多是'move - 1'。 'move'是'len - _switch + 1',所以'i'的最大值是'len - _switch'。因此'i + _switch'的最大值是'len'。 'temp'是'len'字節長,所以索引'len'超出範圍(有效索引是'0'..' len-1')。 – melpomene

+1

'str'是'moveString'中的局部變量。 'str = temp'這個賦值是無用的,因爲它是「死的」:這是'str'停止存在之前函數中的最後一個語句,所以沒有人會看到賦值。 – melpomene

回答

1

你應該注意編譯器警告並消除所有的人。他們的存在是有原因的。

當你編寫你的代碼時,你最有可能得到類似warning: initialization makes integer from pointer without a cast [-Wint-conversion] char arr = "abcdef";這是你的崩潰的原因。

應當char *arr = "abcdef",因爲在"abcdef" C是指針abcdef被寫入存儲器的區域。

但這不是您的程序唯一的問題。真的,看看編譯器的消息,並確保你瞭解什麼是警告,並修復你的代碼不產生任何。

+0

這是一堆意見與一般意見,但不是一個答案。 – Olaf

+0

@Olaf這就是答案。仔細讀。如上所述,將'char arr'改爲'char * arr'將消除崩潰。 – avysk

+0

謝謝@avysk! – Jovani