开发者

C nodes - how to not overwrite the allocated memory space but create new one (homework issue)

Company struct is defined as follows:

typedef struct company {
 char* company_name;
 int employee_counter;
} company;

I use this function to create a new company node:

company *make_company_node(char* company_name, int employee_counter) {
 company *newNode = (company*) malloc(sizeof(company));
 if(!newNode) return NULL; 

 newNode->company_name = company_name;
 newNode->employee_counter = employee_counter;

 return newNode;
}

Then I get some company names from the input, create company node for each one:

c开发者_Go百科ompanyUnion->company_arr[i] = make_company_node(company_name, 0);

(the company_arr eventually contains pointers to all the companies).

The problem is that it seems I'm always overwriting the originally allocated memory space and therefore at the end I wind up with an array whose cells all point to the last company (with the last name submitted).

How can I correct it so that it doesn't overwrite but instead always allocated new space?


If you know the length of company_name before calling your make_company_node function, I'd change the function to accept that length (use strlen otherwise).

company *make_company_node(char *company_name, size_t cn_len, int employee_counter) {
    company *newNode = malloc(sizeof *newNode);
    if (newNode) {
        newNode->company_name = malloc(cn_len + 1);
        if (newNode->company_name) {
            strcpy(newNode->company_name, company_name);
            newNode->employee_counter = employee_counter;
        } else {
            free(newNode);
            newNode = NULL;
        }
    }
    return newNode;
}

I prefer to do it with malloc and strcpy, instead of strdup, because strdup is not defined by the Standard (it is defined by POSIX though), and there's no advantage of using strdup.


If, as pmg mentioned, you know in advance the length of the string or if there is a known maximum number of characters that you can set, prefer defining company_name as a static array instead:

char company_name[MAX_LENGTH];

This will reduce the amount of memory management you need to do, along with potential errors as you just experienced.


Hrm, it seems like the issue is with the company_name variable. This is a pointer to the actual data of the company name. How are you allocating this data? Are you sure it's the right pointer? Maybe you need something like this:

newNode->company_name = strdup(company_name);

strdup duplicates the string you pass to it, dynamically. Don't forget to free it.

This is common error because company_name contains the address of some data. If the same address is used and the data inside it changes, you end up with different results, therefore you need to make a copy of it.


You need to duplicate the company_name string:

newNode->company_name = strdup(company_name);

Don't forget to free() it afterwards.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜