2014-10-11 71 views
0

我做了一個函數,這個做了一個操作,然後寫這個變量,我的問題是: 這段代碼是否安全?此代碼是安全的內存泄漏?

有一個樣品:

#include <stdlib.h> 

void test(char **out){ 
    char *f = (char *) malloc(10); 
    f = "123456"; 
    *out = f; 
    return; 
} 

int main(void){ 
    char *A = NULL; 
    test(&A); 
    free(A); 
    return; 
} 
+3

與字符串工作'F = 「123456」;'是內存泄漏。改爲'strcpy(f,「123456」);' – BLUEPIXY 2014-10-11 18:30:34

+1

你認爲'f =「123456」;'這行是幹什麼的? – 2014-10-11 18:30:40

+0

使用該strncpy來防止緩衝區溢出 – 2014-10-11 18:33:12

回答

0

問題是這裏:

void test(char **out){ 
    char *f = (char *) malloc(10); 
    f = "123456"; 
    *out = f; 
    return; 
} 

malloc的線分配在堆10個字節的內存。所以在這個階段,f的地址將會在malloc碰巧抓住一塊內存的地方。爲了論證的目的,我們會說這是0x10000

然後,你分配f地址的文字字符串。

下面的代碼打印出發生了什麼。

#include <stdlib.h> 

void test(char **out){ 
    char *f = (char *) malloc(10); 
    printf("f after malloc = %p\n", f); 
    f = "123456"; 
    printf("f after re-assignment = %p\n", f); 
    *out = f; 
    return; 
} 

int main(void){ 
    char *A = NULL; 
    test(&A); 
    free(A); 
    return; 
} 

這裏有一些替代方式中C.

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

static char* b = "test 2"; 

void test2(char **out){ 
    *out = b; 
} 

const char* test3(){ 
    return "test 3"; 
} 

void test4(char **out){ 
    *out = (char *) malloc(10); 
    strcpy(*out, "test 4"); 
} 

int main(void){ 
    char *A = NULL; 
    char *B = NULL; 
    char *C = NULL; 

    /* Assign A to the address of a 'global' string */ 
    test2(&A); 
    printf("A is now: %s\n", A); 
    /* Don't free this */ 

    /* return a static string */ 
    B = test3(); 
    printf("B is now: %s\n", B); 

    /* allocate memory on heap and make a copy of data from a source to that memory location */ 
    test4(&C); 
    printf("C is now: %s\n", C); 
    free(C); /* only C is allocated on heap so free this one */ 
} 
0

它泄漏。

使用strcpy爲更緊密地應對串

1

查找到test()定義:

void test(char **out){ 
    char *f = (char *) malloc(10); 
    f = "123456"; 
    *out = f; 
    return; 
} 

尤其是兩條線:

char *f = (char *) malloc(10); 
f = "123456"; 

這段代碼做的是簡單地更換malloc- ed指針與指向字符串的指針,因爲你的程序中有內存泄漏(也就是說,你已經失去了原來的po國際電聯從malloc()獲得),而且呼叫free()(在main()之內)在這種情況下實際上是未定義的行爲。