2016-02-04 30 views
-2

我有一個簡單的程序,其中有一個我在外部寫入的字符串(在這個snippit的情況下,它是用戶創建的)。我正在嘗試利用它的某些部分。將char *轉換爲大寫segfaults

我第一次用分隔符引起它,並試圖使用toupper函數來大寫它,但是我似乎正在得到segfaults。 Valgrind的運行提供任何錯誤,只是簡單地說:

Process terminating with default action of signal 11 (SIGSEGV) 
==10180== Bad permissions for mapped region at address 0x4007B9 

代碼:

int main(void) { 
    char * test; 

    char * f; 
    char * s; 
    char * p; 

    test = "first:second:third:fourth:"; 
    f = strtok(test,":"); 


    for(p = f; *p; *p = toupper(*p), p++); //segfaults 

    printf("f is %s \n",f); //this should print "FIRST" as it should be capitalized 

    return 0; 
} 
+1

'f = s = p = test = malloc(sizeof(char *)* 10);'這是什麼? –

+0

內存泄漏,內存大小不正確...太多... –

+0

@SouravGhosh哇!我沒有看到!當我看到'test = strtok(STRING_LITERAL,...)'我立即回答。 –

回答

2

你不能在一個字符串使用strtok()因爲它改變它的論據,你不能修改一個字符串文字。

也可以修改它在這個循環

for (p = f; *p; *p = toupper(*p), p++); //segfaults 

您需要一個陣列或存儲器的動態分配的塊,這兩者都是可寫的,與所述陣列可以初始化使用字符串文字這樣

char array[] = "This is a string literal, you are not allowed to modify it"; 
/* Now the arest of the code could work but ... */ 

您還需要檢查strtok()的返回值,它是NULL,當它找不到您要查找的內容時。

使用malloc()你也可以這樣做

cosnt char *string_literal = "This is a sample string"; 
size_t length = strlen(string_literal); 
char *buffer = malloc(length + 1); 
if (buffer == NULL) 
    return -1; // Allocation failure. 
memcpy(buffer, string_literal, length + 1); 
//         ^copy the null terminator too 
// Process your newly allocated copy here and, 
free(buffer); 

注意:關於你的原始代碼

f = s = p = test = malloc(sizeof(char *) * 10); 

malloc()沒有用作一般初始化函數,它是用來獲取一個指針到您可以在程序中使用的內存,您可以從中讀取/寫入。當您要求使用malloc()的內存時,您需要在程序中使用特定的(通常精確的)字節數。

如果返回的指針不是NULL,那麼在返回的指針可用時,如果發生錯誤或系統內存不足,將返回NULL

您的代碼,因爲所有的指針fsptest指向相同的內存地址,一個主要的問題還在於你分配可能是或不是你想要的/需要的任意大小。

當你free(f)然後繼續和free(s),你兩次釋放相同的指針,你實際上做的比這更多。在同一個poitner上調用free()兩次會調用未定義的行爲。

+0

Fie!你的代表通過了我! ;-) – chux