jeudi 26 février 2015

free memory used to return value in C



I have a function that calls another function which creates a unique ID and returns it as a string by malloc().


my question is how do I free the memory once outside the function? or what is the better way to do what I would like to do.


my function that asks for the ID:



void addCustomer(TennisStoreType* ts){

CustomerNodePtr newcustdata;
int datapos = 0;

newcustdata = malloc(sizeof(CustomerNodeType));

while (datapos <= CUSTDATA_POSITIONS) {

char userinput[BUFFER_SIZE];

switch (datapos) {
case 0:
strcpy(newcustdata->custID, createCustID(ts));
break;
}
}


the function that returns uniqueID:



char* createCustID(TennisStoreType* ts) {

char *custID;

custID = (char *)malloc(CUSTID_LEN + 1 * sizeof(char));

if (ts->customerCount + 1 >= FOURDIGITS) {
sprintf(custID, "C%i\n", ts->customerCount + 1);

} else if (ts->customerCount + 1 >= THREEDIGITS){
sprintf(custID, "C0%i\n", ts->customerCount + 1);

} else if (ts->customerCount + 1 >= TWODIGITS) {
sprintf(custID, "C00%i\n", ts->customerCount + 1);

} else {
sprintf(custID, "C000%i\n", ts->customerCount + 1);
}

return custID;
}


so how would I go about freeing the string that has been copied to newcustdata->custID? do I even need to? or is there a better way to go about doing this?


thanks in advance.




Aucun commentaire:

Enregistrer un commentaire