Reputation: 368
I keep getting segmentation faults on this code, I'm learning C at the moment.. Can anyone help me out?
Error location:
char *m;
char *as = concat("helloworld", buf);
*m = sha1(as); <<<<<< as
printf("%s\n", m);
free(as);
The concat function (not mine, used for joining 2 strings):
char* concat(char *s1, char *s2)
{
size_t len1 = strlen(s1);
size_t len2 = strlen(s2);
char *result = malloc(len1+len2+1);//+1 for the zero-terminator
//in real code you would check for errors in malloc here
memcpy(result, s1, len1);
memcpy(result+len1, s2, len2+1);//+1 to copy the null-terminator
return result;
}
The sha1 function:
char *sha1( char *val ){
int msg_length = strlen( val );
int hash_length = gcry_md_get_algo_dlen( GCRY_MD_SHA1 );
unsigned char hash[ hash_length ];
char *out = (char *) malloc( sizeof(char) * ((hash_length*2)+1) );
char *p = out;
gcry_md_hash_buffer( GCRY_MD_SHA1, hash, val, msg_length );
int i;
for ( i = 0; i < hash_length; i++, p += 2 ) {
snprintf ( p, 3, "%02x", hash[i] );
}
return out;
}
Since I'm asking, what do they mean with:
//in real code you would check for errors in malloc here
Thanks in advance
Upvotes: 0
Views: 1004
Reputation: 368
The problem was in *m:
char *m = sha1("helloworld"); < OK
*m = sha1("helloworld"); < fail
Upvotes: -2
Reputation: 21435
m = sha1(as);
*m
dereferences the pointer, it means the character under the pointer.
As for malloc
, if it cannot allocate memory if will return a NULL
pointer. You should check for that.
Upvotes: 1
Reputation: 6606
change *m = sha1(as);
to m = sha1(as);
. *m
is a char
value not a char *
.
Now second question:
in real code you would check for errors in malloc here
is all about error handling where you need to check returned pointer from malloc
against NULL
.
Upvotes: 1
Reputation: 25908
sha1()
returns char *
, so you need to change *m = sha1(as);
to m = sha(as);
. *m
is of type char
, not char *
.
Upvotes: 1