这是一个strdup()
用于简化每个新文本行的内存分配的版本。它还使用“x”版本的内存分配函数来简化内存不足错误处理(一个有点常见的习惯用法,即使是非标准的)。
所以真正剩下的所有复杂性(最终不会太多)在于管理字符串指针数组的增长。我认为这使得将处理每个字符串与处理指针数组分开变得更容易。原始代码混淆了这两个领域。
// these variants allocate memory, but abort program on failure
// for simplified error handling - you may need different
// error handling, but often this is enough
//
// Also, your platform may or may not already have these functions
// simplified versions are in the example.
void* xmalloc( size_t size);
void* xrealloc(void* ptr, size_t size);
char* xstrdup(char const* s);
char** receiveCode(int socket){
size_t lines = 0;
char** code = xmalloc( (lines + 1) * sizeof(*code));
*code = NULL;
while(1){
package_struct *aPackage = receivePackage(socket);
if(aPackage->type=='F') {
free(aPackage); // not 100% sure if this should happen here or not.
// Is a `package_struct` with type 'F' dynamically
// allocated or is a pointer to a static sentinel
// returned in this case?
break;
}
// why use `aPackage->size` when you use `strcpy()` to
// copy the string anyway? Just let `strdup()` handle the details
//
// If the string in the `pckage_struct` isn't really null terminated,
// then use `xstrndup(aPackage->package, aPackage->size);` or something
// similar.
char* line = xstrdup(aPackage->package);
++lines;
// add another pointer to the `code` array
code = xrealloc(code, (lines + 1) * sizeof(*code));
code[lines-1] = line;
code[lines] = NULL;
free(aPackage);
}
return code;
}
void* xmalloc(size_t size)
{
void* tmp = malloc(size);
if (!tmp) {
fprintf(stderr, "%s\n", "failed to allocate memory.\n";
exit(EXIT_FAILURE);
}
return tmp;
}
void* xrealloc(void *ptr, size_t size)
{
void* tmp = realloc(ptr, size);
if (!tmp) {
fprintf(stderr, "%s\n", "failed to allocate memory.\n";
exit(EXIT_FAILURE);
}
return tmp;
}
char* xstrdup(char const* s)
{
char* tmp = strdup(s);
if (!tmp) {
fprintf(stderr, "%s\n", "failed to allocate memory.\n";
exit(EXIT_FAILURE);
}
return tmp;
}
另外,我认为应该澄清它aPackage->package
是字符串指针还是char[]
保存字符串数据的实际位置(即,应该&aPackage->package
传递给strcpy()
/ xstrdup()
?)。如果它真的是一个指针,它应该在之前被释放aPackage
吗?