2014-10-11 68 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()之内)在这种情况下实际上是未定义的行为。