2016-12-15 95 views
1

如何在free_x函數內部初始化x?我必須這樣做才能適應API方法。我可以非常容易地通過將null賦值給它來初始化x,但是我必須在free_x函數內部執行它。將null指定給指針的地址

typedef struct 
{ 
    int field1; 
    void *field2; 
}my_struct; 

static my_struct var; 

int main(void) 
{ 
    void *x; 

    alloc_x(&x); 
    free_x(x); // x = NULL works but not allowed 

    return 0; 
} 

void alloc_x(void **param) 
{ 
    *param = (my_struct *)&var; 
} 

void free_x(void *param) 
{ 
    // how can I free param here? 
} 
+5

'* param = NULL;'.......?; – LPs

+2

* param = NULL應該可以工作 –

+0

指針的_address_?或者指針_point_的地址? – byxor

回答

2

簡單的答案:你的代碼已經完成,所以不要再做了。

說明:您不分配內存(在堆或堆棧或其他地方),因此沒有空閒空間。您不必獲取必須返回的任何資源的所有權,設置需要清除的任何標誌,或增加任何需要遞減的信號量等。

您正在實現API,但僅僅是因爲在那裏是一個函數原型,並不意味着你的實現必須做任何事情,如果它不需要的話。只需更改註釋以解釋沒有什麼可做的事情,並將該功能留空。

void alloc_x(void **param) 
{ 
    *param = &var; // No need to cast here, just assign. 
} 

void free_x(void *param) 
{ 
    // Nothing allocated, taken, incremented, etc. in alloc_x, so ... 
    // nothing to free, release, decrement, etc. here in free_x. 
} 

正在使用該API的代碼期待paramx指針後面的內存的調用後已被釋放,因此它不應該在事後反正做其變任何東西。如果他們這樣做,這不是你的問題,但如果你用來調用調用者的x變量,這將是你的問題!

+0

你正在回答一個不是問的問題。而且'struct my_struct'這個問題有一個內部指針,所以可以很容易地猜到其他'malloc'內存必須在'free_x'函數中'free'd。 – LPs

+0

+1對目標。我同意,在這種情況下我們不需要做任何事情。如果調用者在free_x(..)之後使用x,那麼它不是您的問題 –

0

只寫*param = NULL;

的malloc返回void *,並免費取void *的,所以你的一些鑄件是 意義的,你總是騰出一個void *即使你 從一些其他類型的指針開始。

+0

當我寫* param = NULL時,我收到''表達式必須是一個可修改的左值'錯誤! – sanchop22

0

我不認爲它可能沒有改變alloc_x函數。一種可能的實現,給出如下:

#include <stdio.h> 
#include <stdlib.h> 
#include <string.h> 
typedef struct 
{ 
    int field1; 
    void *field2; 
}my_struct; 

static my_struct var; 

void alloc_x(void **param) 
{ 
    *param = malloc(sizeof(my_struct *)); 
    memcpy(*param,(my_struct *)&var,sizeof(my_struct *)); 
} 

void free_x(void *param) 
{ 
    free(param); 
    // how can I free param here? 
} 
int main(void) 
{ 
    void *x; 

    alloc_x(&x); 
    free_x(x); // x = NULL works but not allowed 

    return 0; 
} 
+0

正確但我不能使用malloc和free,因爲我們正在使用微控制器,並且不允許使用動態內存分配儘管這是可能的 – sanchop22

+0

在這種情況下,我可能會問爲什麼你需要alloc_x和free_x?而不是函數爲什麼不使用MACRO像#define free_x(param)param = NULL –

+0

因爲我必須實現free_x函數爲了適應API函數,我必須有free_x(void * param)函數,它應該在函數內部初始化x. – sanchop22

0

一點點triky,但你可以用做

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

typedef struct 
{ 
    int field1; 
    void *field2; 
}my_struct; 

static my_struct var; 

void alloc_x(void **param) 
{ 
    *param = (my_struct *)&var; 
} 

void free_x(void *param) 
{ 
    memset(param, 0x00, sizeof(void *)); 
} 

int main(void) 
{ 
    void *x; 

    alloc_x(&x); 
    printf("Before: x=%p\n", x); 
    free_x(&x); 
    printf("After: x=%p\n", x); 

    return 0; 
} 

void free_x(void *param) 
{ 
    my_struct **p = param; 

    *p = NULL; 
} 

顯然,這是隻適用於void *

+0

這也會毀掉var變量的內容,不知道這是否是有意的 –

+0

This i不好。試圖在另一段代碼中更改* private *值的代碼是設計錯誤或等待發生的錯誤。 –

+0

@MikeofSST是什麼指針指針是用來..... – LPs