I am beginner at UNIX C development and need little bit of help. I have these two functions:
void edit_char(){
int i;
int length = strlen(expression);
char *tmp = (char *) malloc((length+1)*sizeof(char));
pom[0]='*';
for(i=1;i<length+1;i++){
tmp[i] = expression[i-1];
}
strcpy(expression,tmp);
free((void *) tmp);
}
char *edit_char2(char *string){
int i;
int length = strlen(string);
char *tmp = (char *) malloc((length+1)*sizeof(char));
tmp[0]='/';
for(i=1;i<length+1;i++){
tmp[i] = string[i-1];
}
strcpy(string,tmp);
free((void *) tmp);
return string;
}
edit_char() edits global variable char *expression – it puts a symbol “*” at the beginning. Second edit_char2() do almost the same, but instead of editing global variable, it edits string from argument.
First function works fine, the problem is with the tmp variable of second function. Malloc doesn’t return empty char array with size of (length+1). It returns “xd\372\267xd\372\267\020”.
What could cause this?
malloc just returns a pointer to the newly allocated memory, which is not to be considered “empty”. If you want to “empty” it – i.e, fill your memoy with NULLs, you need to
do it manuallyneed to usecallocor fill it manually, for instance with:(deprecated)bzeromemsetEDIT: Also I think that since you are adding a character to each string, you shouldn’t use
but instead
To allocate space both for the new character AND the terminating
\0into account.EDIT2: Which also means that your functions can’t work / are not safe ! You are trying to make both
stringandexpressioncontain 1 more character than they were probably initially allocated for !