C - Segmentation fault in a string to morse code program - c

I've been trying to code a really simple string to morse code converter in C for a few hours now and I finally got it to compile without any warnings. I'm a beginner in C so I really cannot understand how to fix my code. I believe the problem should be in how I pass strings around with pointers and etc, since this is the part I do not understand the most. I found an example on how to do it, but I still couldn't understand it, and there wasn't any specific case that would be similar to mine, since I want it to read strings from the arguments (all arguments are strings/words).
And now I'm getting a segmentation fault when trying to run it:
#include <stdio.h>
#include <ctype.h>
#include <string.h>
int to_morse(char *);
int main(int argc, char **argv)
{
char morse[80];
char *temp;
for (int counter = 1; counter < argc; counter++)
{
*temp = to_morse(argv[counter]);
strcat(temp, morse);
printf("%s", morse);
}
return 0;
}
int to_morse(char *str)
{
char *morse[27] = {".-","-...","-.-.","-..",".","..-.","--.","....","..",".---","-.-",".-..","--","-.","---",".--.","--.-",".-.","...","-","..-","...-",".--","-..-","-.--","--.."};
char *output;
char character;
for (int counter = 0; str[counter] != '\0'; counter++)
{
character = toupper(str[counter]);
strcat(morse[character-'A'], output);
}
return *output;
}
I believe this is not a correct way to pass around strings using pointers, but I cannot figure out the right way. How would I be able to make my code work?
Note: I'm aware this might have a duplicate somewhere.. however, there are tons of segmentation fault questions and all of them are really specific and do not cover my scenario, so I couldn't find one.

There is so much going wrong with your code.
Firstly, strcat takes 2 parameters - a destination and then a source. In all cases that you're using it, you've got them the wrong way around.
Secondly, your function to_morse returns an int when you want it to return a char *. That would be how you pass around pointers.
Thirdly, you don't allocate any memory for output in that function, so even if you had the strcat the right way around, you've not got anywhere to store the morse code. That'll also be where the code is crashing as you're passing in an uninitialised pointer to strcat.
Finally, you should probably check that the character you're trying to convert to morse is a letter, otherwise you'll go out of bounds on your array.
Here is how your code should look. I've also tweaked it so that you put a space between each morse "letter" as otherwise you'd not be able to tell where one begins and another ends.
#include <stdio.h>
#include <ctype.h>
#include <string.h>
#include <stdlib.h>
char *to_morse(char *);
int main(int argc, char **argv)
{
char *temp;
for (int counter = 1; counter < argc; counter++)
{
temp = to_morse(argv[counter]);
printf("%s", temp);
free(temp); // Always remember to free memory you allocate
}
return 0;
}
char *to_morse(char *str)
{
char *morse[27] = {".-","-...","-.-.","-..",".","..-.","--.","....","..",".---","-.-",".-..","--","-.","---",".--.","--.-",".-.","...","-","..-","...-",".--","-..-","-.--","--.."};
char *output=malloc((strlen(str)*5)+1); // Always remember to allocate 1 more char than you need to store the NUL terminate when allocating memory for strings.
output[0] = '\0'; // strcat need a null terminator in the string.
char character;
for (int counter = 0; str[counter] != '\0'; counter++)
{
if(isalpha(str[counter]))
{
character = toupper(str[counter]);
strcat(output,morse[character-'A']);
strcat(output," ");
}
}
return output;
}

Related

Int to char array as a function returning an array of char the simple way

I have been looking on internet for this and so far i just found a lot of questions for specific answer and not a general one.
i am kind of rusty on C. And i want to make a function that will return an array of char.
this is what i got and is not working. basically a way to convert a byte array to an array of chars to do atoi later..
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
char *get_char(int my_byte[], int packetsize)
{
char *array_char=(char *) malloc(sizeof(char)*10); //trying this but didnt work
// char array_char[10]; //i had it like this before(was told to do it)
for(int i=0;i<10;i++)
{
array_char[i]=my_byte[i]+0;
}
return array_char;
}
int main()
{
int byte_array[]={1,2,3,4,5,6,7,8,9,0};
char *temp;
char data;
temp=get_char(byte_array,10);
data=*temp;
printf("String point %s ",data);
}
Two fixes:
As you want to convert to char, then
array_char[i]=my_byte[i]+0; should be array_char[i]=my_byte[i]+'0'; Note '0' is character (that will be converted to int) instead of numeric 0 (which doesn't do anything).
Also you must free temp pointer in main as that memory is dynamically allocated in get_char() function.
Edit: just notice another issue in your get_char()
char *array_char=(char *) malloc(sizeof(char)*10);
should be
char *array_char= malloc(sizeof(char)*(packetsize+1));
After the for loop, ensure the buffer is NUL-terminated:
array_char[packetsize] = '\0';
Notice that your packetsize is never used - you should get some compiler warning about it. It's bad to hard code 10 in your malloc - it's actually the whole idea of parsing the packetsize as a parameter - so use it properly.
You need to watch out for these things:
You need to add a null-terminating character at the end of *array_char, otherwise using this pointer allocated from the heap will cause undefined behaviour.
You can simply allocate *array_char like this:
char *array_char = malloc(packetsize+1);
As sizeof(char) is 1, and +1 for trailing nullbyte.
You also don't need to cast return of malloc().
Instead of passing 10 as packetsize to get_char(), you should pass this size as sizeof(arr) / sizeof(arr[0], which is the calculated size of the array. This can be a size_t variable declared somewhere or even a macro.
malloc() needs to be checked, as it can return NULL if unsuccessful.
You need to free() temp at some point in the program.
array_char[i]=my_byte[i]+0; needs to be array_char[i]=my_byte[i]+'0'; instead, as '0' is the ascii code for a zero character.
char data needs to be char *data, as temp is a pointer.
If you compile with -Wall -Wextra, you will see that this line:
data=*temp;
Is dangerous, and will trigger warnings of making pointers from integers without a cast. It will most likely lead to a segmentation fault. If temp and data are both pointers, then you can simply use:
data=temp;
Which sets data to the address of temp. Sometimes this is written as data = &(*temp);, but this is harder to read. Although their is no need for data, and using temp alone should be fine.
Your code can then look like this:
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
#define ARRAYSIZE(arr) (sizeof(arr) / sizeof(arr[0]))
char *get_char(int my_byte[], size_t packetsize) {
char *array_char = malloc(packetsize+1);
const char ascii = '0';
size_t i;
if (!array_char) {
printf("Cannot allocate %zu bytes\n", packetsize+1);
exit(EXIT_FAILURE);
}
for(i = 0; i < packetsize; i++) {
array_char[i] = my_byte[i] + ascii;
}
array_char[i] = '\0'; /* or array_char[packetsize] = '\0' */
return array_char;
}
int main(void) {
int byte_array[]={1,2,3,4,5,6,7,8,9,0};
char *temp, *data;
temp = get_char(byte_array, ARRAYSIZE(byte_array));
data = temp;
printf("String point %s\n", data);
printf("String converted into number = %d\n", atoi(data));
free(temp);
temp = NULL;
return 0;
}
You can also look into strtol, which is better than using atoi() in terms of error checking.
It is Not Wise Idea to Return a Array From A Function. So how to return a string then? As most of libc functions use we can use some thing like that (i.e) passing a buffer along with our input and expect function to use output buffer to give us result.
Some issue to take care while coding
write your logic first.
try to use available functions from libc.
while dealing with byte data/binary data be take precaution of buffer overflow.
don't allocate in a function and de-allocate in another function.
Below is Example of your code with modification.
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
#include <stdint.h>
int get_char(uint8_t my_byte[], int packetsize, char *buffer, int max_buffer)
{
int byte_itr, buf_itr;
char temp_buf[16]={0x00};
for(byte_itr=0, buf_itr=0; byte_itr<packetsize && max_buffer > buf_itr; byte_itr++)
{
memset(temp_buf, 0x00, sizeof(temp_buf));
char temp_ch = my_byte[byte_itr];
snprintf(temp_buf, sizeof(temp_buf), "%d", temp_ch);
if( buf_itr+strlen(temp_buf) >=max_buffer){
break;
}else{
buf_itr += strlen(temp_buf);
strcat(buffer, temp_buf);
if(byte_itr+1 < packetsize){
strcat(buffer, ",");
buf_itr += 1;
}
}
}
return buf_itr;
}
int main()
{
uint8_t byte_array[]={1,2,3,4,5,6,7,8,9,0};
char char_array[32]={0x00};
int len = get_char(byte_array, 10, char_array, sizeof(char_array));
printf("String point %s : len %d\n", char_array, len);
}
NOTE:
when length return and size of output buffer same then buffer full condition happened.

What's wrong with my code function to make strcat function in C?

#include <stdio.h>
#include <stdlib.h>
char wordsum(char FW[256],char SW[256]){
int i;
int j=strlen(FW);
for (i=0;i<=strlen(SW);i++)
FW[i+j+1]=SW[i];
printf("%c",FW);
return FW;
}
int main()
{
char F[256];
char S[256];
printf("Enter the first word\n");
gets(F);
printf("Enter the Second word\n");
gets(S);
wordsum(F,S);
return 0;
}
I don't know what is wrong with my code to make strcat function. I hope to find the answer.
I assume that the code is written to learn more about the C language. If so, may I present an alternative implementation which does not use strlen(). The intention is to present some of the really nice features in the language. It may be a bit complicated to wrap ones head around the first time, but IIRC the code can be found in K&R's book The C Programming Language.
Here we go:
char* mystrcat(char *dest, const char *src)
{
char *ret = dest;
while (*dest)
dest++;
while ((*dest++ = *src++))
;
return ret;
}
The first while-loop finds the end of the destination string. The second while-loop appends the source string to the destination string. Finally, we return a pointer to the original dest buffer.
The function could've been even nicer if it didn't return a pointer.
void mystrcat(char *dest, const char *src)
{
while (*dest)
dest++;
while ((*dest++ = *src++))
;
}
HTH
There are several mistakes in your code. They are:
1) A function can't return an array in C and you don't need to do so. Change the return type from char to void of wordsum and erase the line return FW;
2) You want to print a string, right? Format specifier for string is %s. So write printf("%s",FW); instead of printf("%c",FW);.
3) Do this: FW[i+j]=SW[i];. Why did you add an extra 1 to i+j? Just think logically.
4) Add header file for strlen(), it's <string.h>.
5) Erase those asterisk marks before and after FW[i+j]=SW[i];.
There are a few problems in your function, I've changed and commented them below:
char *wordsum(char FW[256],char SW[256]){ // correct function type
int i;
int j=strlen(FW);
for (i = 0; i <= strlen(SW); i++)
FW[i+j] = SW[i]; //change 'i + j + 1' to 'i + j'
printf("%s",FW); //change format specifier as you are printing string not character
return FW;
}
Then dot forget to capture the returned pointer using a char* variable in the calling function (here main())
char *result;
result = wordsum(F,S);
printf("\n%s\n", result);
Working example: https://ideone.com/ERlFPE

Producing uppercase letters without pointers

I am trying to write a function, uppercase, that converts all lowercase characters in a string into their uppercase equivalents.
However, I am getting a Bus 10 error in my code. I know that string literals cannot be modified in C; so, I am not sure if this is the right approach.
My code is below:
#include <stdio.h>
#include <stdbool.h>
#include <stdlib.h>
#include <string.h>
int uppercase(char source[])
{
int i;
for(i=0; i<=strlen(source); ++i)
if (source[i]>= 'a' && source[i]<= 'z')
source[i]= source[i]-'a' +'A';
else
source[i]=source[i];
}
int main(){
uppercase("cold");
return 0;
}
Ideally this function should return COLD.I suppose the error lies in my whole if statement.
The reason you get a crash is that your code modifies a string literal. Characters inside string literals are placed in protected memory area, and therefore may not be changed: it us undefined behavior.
Replace this
uppercase("cold");
with this:
char cold[] = "cold";
uppercase(cold);
Now the characters of the string are placed in a modifiable area of memory, allowing you to make changes as needed.
Your absolutly working with pointers without even to know it.
In your function definition
int uppercase(char source[])
char source[] is considered by the compiler as a pointer to char (char *source)
So when passing a string literal to uppercase() your just passing it's adress. Then in your function your trying to modify it which leads to undefined behaviour.
Also you can't return a whole array so you just return a pointer to it.
char *uppercase(char source[])
{
int i;
size_t len = strlen(source);
char *tmp;
tmp = malloc(len+1);
if (tmp!=NULL){
memcpy(tmp, source, len+1);
for(i=0; i<len; ++i){
if (tmp[i]>= 'a' && tmp[i]<= 'z'){
tmp[i]= tmp[i]-'a' +'A';
}
}
}
return tmp;
}
Then:
int main(){
char *str = uppercase("cold");
printf("%s", str);
free(str);
return 0;
}
You complete code: http://ideone.com/BJHDIF

C function to capitalize first letter of words in an array

I'm pretty new to C and am hitting a wall when creating the below function. I want to use this function to make the first letter of a word upper case for a static character array (char string[]. It looks ok to my eye, but I'm getting some syntax errors which are probably pretty basic.
compiler errors:
error: invalid conversion from const char' toconst char*'
initializing argument 1 of `size_t strlen(const char*)'
assignment of read-only location
void Cap(char string[]){
int i;
int x = strlen(string);
for (i=1;i<x;i++){
if (isalpha(string[i]) && string[i-1] == ' '){
// only first letters of a word.
string[i]= toupper(string[i]);
}if (isalpha(string[0]))
{
string[0]=toupper(string[0]);
}
}
}
you might want to run strlen(string) - as strlen(string[i]) is trying to get the length of a single char.
I will also point out your braces don't match ...
if (isalpha(string[i])){
string[i]= toupper(string[i]);
Remove brace on the if line or put a close brace after your assigning statement.
I took your code and tried to compile it. Well, it would be nice to see compilable code the next time. Here is one with comments.
#include <stdio.h> // Now I am able to use printf.
#include <string.h> // I was not able to use strlen without this...
void Cap(char string[]){
int i;
int x = strlen(string); // You want to get the length of the whole string.
for (i=1;i<x;i++){
if (isalpha(string[i]) && string[i-1] == ' '){
// only first letters of a word.
string[i]= toupper(string[i]);
}
}
}
main(){
char string[] = "text with lowercase words.";
Cap(string);
printf("%s",string);
};
Still the first word of the text is lowercase. This is a task for you.
You're missing the closing curly brace for your if statement. This might just be a typo in the question, but mentioning it just in case.
Your function is declared void. This means it returns nothing. Any return statement should have nothing after the word since the function returns nothing, and in many cases you won't have a return statement at all.
However, the biggest issue is that this isn't an array of strings. It's an array of chars, which is just one string. char* string and char string[] both (potentially) refer to an array of characters, which makes up a single string. You would need to use another level of indirection to refer to an array of array of characters: char** strings, char* strings[], or char strings[][]. The last form would require you specify how long all the strings could be, so you'd usually only use the first two.
The problem here is that you are passing in a single string, not an array of strings.
Basically in C, a string is an array of chars, hence an array of strings is a two dimensional array like so:
const char* strings[];
There are a few other issues with the code. You haven't initialized i before using it.
A alternate approach: (write a function)
1) (optional) Allocate memory for new buffer of same length for results in calling function.
2) In function - Set first char of new string to upper case version of original string
3) Walk through the string searching for spaces.
4) For each space, Set next char of new string to upper case of char in original string
5) Loop on 4) until NULL detected
6) Free any allocated memory in calling program.
Code example:
void capitalize(char *str, char *new)
{
int i=0;
new[i] = toupper(str[0]);//first char to upper case
i++;//increment after every look
while(str[i] != '\0')
{
if(isspace(str[i]))
{
new[i] = str[i];
new[i+1] = toupper(str[i+1]);//set char after space to upper case
i+=2;//look twice, increment twice
}
else
{
new[i] = str[i];//for no-space-found, just copy char to new string
i++;//increment after every look
}
}
}
This should work just fine.
#include <stdio.h>
#include <string.h>
capital(char s[])
{
int i;
for(i=0; i<strlen(s); i++)
{
if (i==0||s[i-1]==' '&&s[i]>='a'&&s[i]<='z')
s[i]=toupper(s[i]);
}
puts(s);
}
main()
{
char s[100];
printf("Enter a line: ");
gets(s);
capital(s);
}
I made an update based on Stefan Bollmann answer:
#include <string.h>
#include <stdio.h>
char* uc_words(char string[])
{
int i;
int x = strlen(string);
int counter = 0;
for (i = 0; i < x; i++)
{
// If found a white-space reset counter
if (isspace(string[i]))
counter = 0;
// Check if first character in word
if (isalpha(string[i]) && !isspace(string[i]) && counter == 0)
{
string[i]= toupper(string[i]);
counter = 1;
}
}
return string;
}
int main()
{
char string[] = "hello world";
printf("%s\n", uc_words(string));
return 0;
}

Creating a simple String Struct

So i'm trying to create a simple String struct which will contain the text of the string and the size of it, at least for now. However I'm having issues allocating my struct. Right now i'm simply trying to get a size of 1 character to work, but its simply crashing at this point and i don't know what i'm doing wrong with the allocation, please help.
#include <stdio.h>
#include <stdlib.h>
typedef struct{
char* text;
int size;
}String;
String* getString();
int main(int argc, char** argv){
String* str1 = getString();
printf("%s",str1->text);
free(str1);
return 0;
}
String* getString(){
String* str = (String*)malloc(sizeof(String));
scanf("%s",str->text);
str->size++;
return str;
}
You need to allocate memory for the structure but also for text string.
scanf("%s",str->text);
str->text is an uninitialized pointer.
You don't allocate any memory for str->text. You leave it uninitialized, so your program invokes undefined behavior.
You need to allocate memory for it using str->text = malloc(MAX_SIZE); where MAX_SIZE is the maximal size for the string. Alternatively, if your strings will be short, you may use a regular, fixed-szie array instead.
Furthermore, you probably do not want to use scanf() for scanning strings. One particular reason is that %s makes scanf() stop at the first whitespace character. Another reason is that it's not trivial to prevent scanf() from writing past the buffer if it's too small.. How about using fgets() instead?
fgets(str->text, MAX_SIZE, stdin);
is a better and safer approach.
int main(int argc, char** argv){
String* str1 = getString();
printf("%s",str1->text);
free(str1->text);
free(str1);
return 0;
}
String* getString(){
String* str = (String*)malloc(sizeof(String));//for struct
str->size = 16;//initialize
str->text = (char*)malloc(sizeof(char)*str->size);//for input text
int ch, len;
while(EOF!=(ch=fgetc(stdin)) && ch != '\n'){
str->text[len++]=ch;
if(str->size==len){
str->text = realloc(str->text, sizeof(char)*(len+=16));
}
}
str->text[len++]='\0';
str->text = realloc(str->text, sizeof(char)*(str->size=len));
return str;
}

Resources