Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 8 years ago.
Improve this question
I have a question regarding concatenating two strings in C to say "Ring Ding"
I have one char * d which I malloc 14*sizeof(char) just to stay on the safe side to include the \o characters at the end, but my function is still segfaulting, and I'm not sure why. It says I cannot implicitly define strcopy. I'm thinking my problem is that I can't just come out and say "Ring", but I could be mistaken.
char * k = malloc(14*sizeof(char));
strcopy(k, "Ring");
strcat(k, "Ding");
printf("%s\n", k);
There is a typo for 'strcopy'; it is usually 'strcpy' from string.h
As C allows you to call functions without declaring them first, you got the warning for the 'Implicit declaration' as it was not found int string.h.
I am surprised you were able to run the program as you should have got a linker error as it could not find the definition of the function.
If you fix the typo, it should compile and run fine.
I would also recommend to use the strl* versions of these string functions (strlcpy, strlcat etc..) - it is much safer; see the man page.
Suppose you have:
char* str1 = "Ring";
char* str2 = "Ding";
Follow these steps (as a general rule):
// Function 'strlen' always returns the length excluding the '\0' character at the end
// The '+1' is because you always need room for an additional '\0' character at the end
char* k = (char*)malloc(strlen(str1)+strlen(str2)+1);
// Write "Ring\0" into the memory pointed by 'k'
strcpy(k,str1);
// Write "Ding\0" into the memory pointed by 'k', starting from the '\0' character
strcat(k,str2);
// Print the memory pointed by 'k' until the '\0' character ("RingDing") to the console
printf("%s\n",k);
// De-allocate the memory pointed by 'k'
free(k);
I hope this code help you!
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main()
{
char * k = (char*)malloc(14*sizeof(char));
strcpy(k, "Ring");
strcat(k, "Ding");
printf("%s\n", k);
return 0;
}
Related
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 3 years ago.
Improve this question
I am trying to write a program that converts a string to morse code. It currently works fine whenever input is a string literal but whenever I send a string as a variable I get a segmentation fault.
void morseCode(char* s)
{
for (int i = 0; s[i]!='\0'; i++)
printf("%s",morseEncode(s[i])); //morseEncode is a function which returns char* of morse code
}
int main()
{
int length = strlen("Hello");
char* s = (char*) malloc(length + 1);
s = "Hello";
morseCode(s); // Segmentation fault
morseCode("Hello"); // works fine
return 0;
}
This is a result of passing the variable s to morseEncode (which presumably modifies it) as modifying s is undefined behaviour. Specifically, modifying a string literal in such a manner is undefined behaviour per 6.4.5p6 [from C99:TC3]
It is unspecified whether these (string literal) arrays are distinct provided their
elements have the appropriate values. If the program attempts to
modify such an array, the behavior is undefined.
(text in parentheses added by me)
You might also want to take a look at this question.
You could instead declare s like so (with automatic storage duration).
char s[] = "Hello";
If you need s to be a pointer you could try
// Yes, sizeof(char) will always be 1 and you could remove it.
char *s = malloc(sizeof(char) * (strlen("Hello") + 1));
strcpy(s, "Hello");
// Your code that uses s here
free(s) // Important!
As an additional note #kaylum has pointed out that the original answer didn't provide a justification as to why calling the function in the two different ways produced different results. This is because the undefined behaviour you're running into just so happened to be undefined in a different way for each call. If I write out a similar program and compile it using gcc (with no flags) I end up running into a segfault both ways; on the other hand, compiling with clang -O both work! Its simply a product of whatever segment(s) of memory your specific compiler has decided you place each of those sequences of characters.
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 4 years ago.
Improve this question
I dunno why this doesn't work. the code has a problem with the *c in
charToInt function but should be a legal statement in c. at least so I thought. I am excited to learn something new here.
int charToint(char *c) {
return *c - '0';
}
int main(void) {
char c = '3';
printf("%d\n", charToint(c));
{
You're passing a char to a function that expects a char *. Your compiler should have warned you about this. The value of that char is then interpreted as a pointer value and dereferenced. Dereferencing an invalid pointer invokes undefined behavior, which in this case results in the program crashing.
The function is ultimately trying to work with a char, so change it to accept a char:
int charToint(char c) {
return c - '0';
}
Alternately, you can leave the function as it and pass it a pointer:
printf("%d\n", charToint(&c));
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 7 years ago.
Improve this question
i need to detect the problem in the next code, and the reason to that problem and how to fix it. for some reason when i tried to run it in visual the error is on the free.
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <malloc.h>
int main()
{
char str1[] = "abcde";
char* str2 = (char*)malloc(strlen(str1));
strcpy(str2, str1);
puts(str1);
puts(str2);
free(str2);
return 0;
}
strlen return the length of null terminated string excluding the null character '\0'. You need to allocate space for null character too.
char* str2 = malloc(strlen(str1) + 1); // Do not cast return value of malloc
it should be
char* str2 = (char*)malloc(strlen(str1)+1);
The issue, as others have mentioned, is that you're not allocating enough space for the string you want to copy. strlen returns the number of characters in the string, however that number doesn't include the null byte at the end that terminates the string.
So when you call strcpy, you're writing one byte past the end of the allocated memory. Once you write past your memory bounds, that invokes undefined behavior. That means your program might appear to work, it might crash (sometimes right away, sometimes later), or it might cause data corruption that would be hard to detect.
In this particular situation, the extra byte you wrote probably corrupted data used by the implementation of free and/or malloc. But with some other compiler or OS, it might work fine.
So to avoid undefined behavior, be sure to allocate the required amount of space:
char* str2 = malloc(strlen(str1) + 1);
Also, don't cast the return value of malloc, as that may mask other errors in your code.
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 8 years ago.
Improve this question
it seems that this is a duplicate question, but I searched stackoverflow's question about that point and non is like to my problem(I think)
I've two variables of a struct each has its own pointer to char, when I tried to copy from one variable's string to another variable's string, nothing happened, although no errors appear, just warning
implicit declaration of function strcpy
incompatible implicit declaration of built-in function 'strcpy'
I read from some questions on stackoverflow that you'd better to use strdup() function instead of strcpy() but when I did, I had an error
too many arguments to function 'strdup'
I read that there's a problem with strcpy() called "segmentation fault" and I knew it's about memory allocation, I don't totally understand what it's exactly and don't know if it's the problem with my code?
and this is my code
struct p
{
char *name;
struct p *next;
};
struct p *ptrary[10];
int main(void)
{
struct p p,q;
p.name="xyz";
p.next=NULL;
ptrary[0]=&p;
strdup(q.name,p.name);
ptrary[1]=&q;
printf("%s\n",ptrary[1]->name);
return 0;
}
so what is the problem and how I can solve it?
strdup() takes only one argument; it malloc's and returns a new block of heap memory containing the duplicated string. (See https://stackoverflow.com/questions/252782/strdup-what-does-it-do-in-c)
Which probably also points to the problem you were having before -- were you remembering to malloc the space for q to copy p's contents into?
change
strdup(q.name,p.name);
to
q.name = strdup(p.name);
see man page of strdup for further details. The strdup() function returns a pointer to a new string.
full code:
#include <stdio.h>
#include <string.h>
struct p
{
char *name;
struct p *next;
};
struct p *ptrary[10];
int main(void)
{
struct p p,q;
p.name="xyz";
p.next=NULL;
ptrary[0]=&p;
q.name = strdup(p.name);
ptrary[1]=&q;
printf("%s\n",ptrary[1]->name);
return 0;
}
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Closed 8 years ago.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Improve this question
I have a little problem with casting int to char* (string)... is it even possible in C?
I'll try to explain why i need this.
I can cast int to char but I need cast int to char*.
I had a int varriable (int number_of_revisions)
and I need convert this number of revisions to char * becouse I need create a name of file and the number of revision is part of the name.... so there is part of code for better imagination of this problem.
int number_of_revision = 970; // 970 just for example
char * version;
char * new_name;
char ch_number_of_rev[4];
version = "0.";
itoa(number_of_revision,ch_number_of_rev,10);
//strcat(version, ch_num_o_rev ); // doesn't work becouse ch_number_of_rev is char and strcat requires char*
please I need quick help... Have anybody any idea how to do it? ...
but I need cast int to char*
Casting only changes the type - it does not change the value within the variable. If you need to convert an int to array of chars (i.e. a string) then use sprintf or snprintf:
char* buffer = ... allocate a buffer ...
int value = 970;
sprintf(buffer, "%d", value);
Converting int to string in c
Also, you have not allocated any memory for version - use malloc and allocate some memory.
strcat here won't work because you haven't allocated any space to store the result in. Your version is probably in read-only memory anyway, so you'd get a segfault, otherwise you'll get memory corruption. So make sure to allocate enough space for it, e.g. by using
char version[10] = "0.";
You may want to read up on pointers first, though.