Yes, you created a structure on the heap. You didn’t populate it correctly, and you will have problems with deleting it - I’m not sure whether this covered homework or not. Be that as it may, you are more likely to get a memory corruption or, with luck, a memory leak, than to release one of these lines.
Code that works with standard C89 and C99
Your code, slightly corrected ...
typedef
struct String {
int length;
int capacity;
char *ptr;
} String;
char* modelstrdup(char* src){
int length = strlen(src);
char *space = malloc(sizeof(String) + length + 1);
String *string = (String *)space;
assert(space != 0);
string->ptr = space + sizeof(String);
string->length = length;
string->capacity = length + 1;
strcpy(string->ptr, src);
return string->ptr;
}
C89, C99 ( C99/++). , "struct hack" ( , C99). . . , - , .
, , , . .
, C99
C99 6.7.2.1 16 " ":
; . , . -, , . 106) -, a. ( → ) , ( ) , , ( ), , ; , . , , , undefined, - .
106 , , .
"struct hack" " ", :
typedef
struct String {
int length;
int capacity;
char ptr[];
} String;
char* modelstrdup(char* src){
int length = strlen(src);
String *string = malloc(sizeof(String) + length + 1);
assert(string != 0);
string->length = length;
string->capacity = length + 1;
strcpy(string->ptr, src);
return string->ptr;
}
GCC 4.0.1, ( "-Wall -Wextra" ). String * string = (String *); , , ; , .
, C89 C99
GCC, - ISO C . , , "gcc -Wall -Wextra -std = c99 -pedantic":
#include <assert.h>
#include <stdlib.h>
#include <string.h>
typedef
struct String {
int length;
int capacity;
char ptr[0];
} String;
char* modelstrdup(char* src){
int length = strlen(src);
String *string = malloc(sizeof(String) + length + 1);
assert(string != 0);
string->length = length;
string->capacity = length + 1;
strcpy(string->ptr, src);
return string->ptr;
}
, C , C. ; , , , , . , , . C , , .