I get no compiler warning from this but it segfaults. So how can I copy a '\0' at the beginning of the string so I can then use strncat ? (The use of strncpy is not allowed and using memcpy and then terminating the string segfaults also.)
I wrote this to illustrate the problem:
void func(char **str)
{
*str = realloc(*str, -);
*str[0] = '\0'; // I get segfault here.
strncat(*str, -, -);
// memcpy(*str, -, -);
// *str[strlen(*str)] = '\0';开发者_JAVA百科 // I get segfault here.
}
int main(void)
{
char *str = NULL;
func(&str);
return 0;
}
EDIT: I meant to write strlen(*str) and not strlen(str). Sorry.
The problem with the second segfaulting line is operator precedence.
[]
has higher precedence than *
, so *str[strlen(*str)]
is interpreted as *(str[strlen(*str)])
- that is, dereference the address pointed to by the memory at str + strlen(*str)
.
You want (*str)[strlen(*str)]
- that is, the character at the end of of str
-dereferenced.
Segmentation faults occur when the memory being accessed by the program is invalid. It is very likely that the realloc call was not able to allocate the amount of memory being requested. It is a best practice to check whether the memory is properly allocated before proceeding to access it.
I tried this program and works well in my system.
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
void func(char **str)
{
*str = realloc(*str, sizeof(char) * 20);
if( *str == NULL)
{
printf("Memory allocation failed\n");
return;
}
*str[0] = '\0';
strncat(*str, "hello world", 11);
//memcpy(*str, "hello world", 11); //memcpy also works fine
//(*str) [strlen(*str)] = '\0';
printf("String : %s\n", *str);
}
精彩评论