Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Malloc a string array - C

Tags:

arrays

c

string

I have been trying to understand malloc and strings, can someone help me with this please - I get a bad pointer error

char password[100];
char *key[2];   
int textlen, keylen, i, j, k, t, s = 0;

printf("password:\n") ;   
scanf("%s",password);

keylen = strlen(password) + 1;

for(i=0; i < keylen; i++)
{                
    key[i] = (char*)malloc(keylen * sizeof(char));
    strcpy(key[i], password);
}

printf("The key is:\n\t %s", key);
like image 546
Dex Dave Avatar asked Sep 20 '13 12:09

Dex Dave


2 Answers

I think you need to try and understand yourself what you are trying to achieve. You don't need the key[2] array and I think you are confusing yourself there as you don't yet understand how pointers work. The following should work (untested)

// Allow a password up to 99 characters long + room for null char
char password[100];
// pointer to malloc storage for password
char *key;   
int textlen, keylen, i, j, k, t, s = 0;

// Prompt user for password
printf("password:\n") ;   
scanf("%s",password);

// Determine the length of the users password, including null character room
keylen = strlen(password) + 1;

// Copy password into dynamically allocated storage
key = (char*)malloc(keylen * sizeof(char));
strcpy(key, password);

// Print the password
printf("The key is:\n\t %s", key);
like image 147
djgandy Avatar answered Nov 03 '22 09:11

djgandy


The problem that you have is here:

 printf("The key is:\n\t %s", key);

You are passing the pointer array to printf, while what you would want to do is

 printf("The key is:\n\t %s", key[0]);

Yet another problem is that you allocte as much pointers as you have characters in your password, so you overwrite the pointer array you reserved, because key has only room for two pointers, not for N, which is the primary cause for your "bad pointer" problem.

And another thing, which is not related to this error is, that you shouldn't cast malloc as well as you don't need to multiply with sizeof(char) as this will always be 1 by definition.

like image 43
Devolus Avatar answered Nov 03 '22 10:11

Devolus