I only want to know if it is the right direction, not if it makes perfect sense.
Here is the code:
- Code: Select all
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
void print_strings(char *original, char *copy);
int main(int argc, char *argv[])
{
char *orig = (char *)malloc(strlen("hello")+1);
if ( orig == NULL ) {
puts("error: oom"); //oom: out of memory
return 1;
} else {
strcpy(orig, "hello");
}
char *copy = (char *)malloc(strlen("h")); //what the feck was that supposed to do??? probably something with realloc
char *newcopy = (char *)malloc(sizeof(orig));
if ( newcopy != NULL ) {
copy = newcopy;
} else {
puts("error: out of memory");
return 1;
}
strcpy(copy,orig);
print_strings(orig, copy); //dang, no error message, this way or that way
//... grml
return 0;
}
void print_strings(char *o, char *c)
{
printf("original: %s\ncopy: %s\n", o, c);
}
My questions are the following:
If i want to put a string in a char-array, is the usage of malloc right:
char *orig = (char *)malloc(strlen("hello")+1);
If i want to make a second char-array, of the same size like an existing one, is this right:
char *newcopy = (char *)malloc(sizeof(orig));
(i mean using sizeof(the_char-array_size_i_want).
Last but not least: I could swear i have read that i need to check the return value of free().
If i try it fails. I searched the web, but ... well: search for something with "free", and you know what problems i got)
Any clear word on memory allocation are welcome (i think i am getting closer, but would not bet).
Thanks


