simple string runtime error in C? - c

This code compiles fine but give segmentation fault error while running? Can anyone tell why?
#include <stdio.h>
#include <string.h>
#include <math.h>
int main() {
const char s2[] = "asdfasdf";
char* s1;
strcpy(s1, s2);
printf("%s", s1);
return 0;
}

You allocated space for a single pointer, s1, but not the bytes pointed at by s1.
A solution is to dynamically allocate memory for s1:
s1 = (char *)malloc(strlen(s2) + 1);
strcpy(s1, s2);
Keep in mind that you need to allocate one more byte of memory (the +1 in the call to malloc) than the number of characters in s2 because there is an implicit NULL byte at the end.
See C Memory Management (Stack Overflow) for more information.

You didn't allocate memory for s1. You have a pointer to s1 but no memory allocated for the strcpy to copy the value of s2 into.
char *s1 = malloc( strlen(s2) + 1 );
strcpy( s1, s2 );

You have not allocated any memory to s1. It is a pointer to nothing.
char* s1 = malloc(sizeof(s2));
strcpy(s1, s2);
printf("%s", s1);
free(s1);

The problem is that s1 does not have any memory associated with it. strcpy does not call malloc().
You could either do:
char s1[10];
or
char *s1 = malloc(10);

What they all said, you need to allocate the space for s1. What everyone else has posted will work just fine, however, if you want a simpler way to allocate space for an existing string and copy it into a new pointer then use strdup like this:
#include <stdio.h>
#include <string.h>
#include <math.h>
using namespace std;
int main() {
const char s2[] = "asdfasdf";
char* s1;
s1 = strdup(s2);
printf("%s", s1);
return 0;
}
Someone mentioned strdup earlier, that would be a way to use it. Most systems should support it since it is in the standard C libaries. But apparently some don't. So if it returns an error either write your own using the method already mentioned, or just use the method already mentioned ;)

No one yet has pointed out the potential of strdup (String Duplicate) to address this problem.
#include <stdio.h>
#include <string.h>
#include <math.h>
using namespace std;
int main() {
const char s2[] = "asdfasdf";
char* s1;
s1 = strdup(s2); // Allocates memory, must be freed later.
printf("%s", s1);
free(s1); // Allocated in strdup, 2 lines above
return 0;
}

You need to allocate the destination (and using namespace std; isn't C but C++, the rest of the code is C).

You have to allocate memory to the pointer s1. If you don't do that, it will be pointing somewhere unknown, and thus arriving at the segmentation fault. The correct code should be:
#include <stdio.h>
#include <string.h>
#include <math.h>
int main() {
const char s2[] = "asdfasdf";
char* s1 = malloc(21 * sizeof(s2[0]));
strcpy(s1,s2);
printf("%s",s1);
return 0;
}

Related

How to assign an array of characters to a string literal

I have an array of char and I'm trying to have a string literal with the same chars in the array.
I tried strcpy, and try =, and I tried what I did in the following code. But it doesn't seem to work or I'm understanding something.
char s1[10]="Youssef";
char *s2
while(*s2!='\0')
*s2++=*s1++;
printf("%s",s2);
Process doesn't return.
String literals are read only.
In any case, what you are trying to do seems you are confused.
A string literal: char *sl = "string literal";
An uninitialized char pointer: char *s2;
In order to do the copy you like, you first need to allocate memory for the string.
Moreover, you cannot do pointer arithmetics with an array. Arrays and pointers are not the same thing!
Furthermore, you should remember the origin of s2 pointer, since after incrementing it until the copy is complete, you would then need to reset the pointer.. Exercise: Think what would happen if you did the copy in a function (preferably named mystrcpy`)...
Complete example:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(void) {
char s1[10]="Youssef";
char *s2 = malloc(sizeof(char) * (strlen(s1) + 1)); // +1 for the NULL-terminator
int i = 0;
char *origin_s2 = s2;
while(s1[i] != '\0')
*s2++ = s1[i++];
*s2 = '\0';
s2 = origin_s2;
printf("%s\n", s2);
return 0;
}
Output:
Youssef
PS: It is highly recommended to check if the dynamic allocation of the memory was successful (check if return value of malloc() is not NULL).

Memory fault and pointer to string

So I'm trying to reverse a string, but I get a memory fault. Memory for s and s1 is initialized enough to accomodate the '/0' character as well.
Interestingly if I remove *s=*s1 and print s1 instead the program works.
But I haven't even set the "\0" character at the end of s1 so how does it even know where to stop printing?
And in the case below what exactly is the issue?
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
void main(void)
{
char *s = "abcdefghijklmnop", *s1=malloc(17);
int i;
for(i=0;i<strlen(s);i++)
{
*(s1+i) = *(s+strlen(s)-1-i);
}
*s=*s1;
printf("%s",s);
}
The char *s = "abcdefghijklmnop" is a string literal which is often in read-only memory.
An error will be generated if you attempt to modify a string literal.
You attempt to replace the first character in s with the first character in s1 when you do *s=*s+1.
If s wasn't a string literal, you should've done s=s1 instead of *s=*s1 to make s its reverse.
More about this:
https://softwareengineering.stackexchange.com/questions/294748/why-are-c-string-literals-read-only
String literals: Where do they go?
where in memory are string literals ? stack / heap?
The correct string is printed with printf("%s", s1); even if no \0 was stored because the memory next to the last character just happened to be 0 which is equivalent to \0. This needn't always be so and cannot be relied upon as malloc() doesn't initialise the memory that it allocates.
But calloc() will initialise the memory it allocates to 0.
See more here.
In your code *s=*s1 only copy the first content of s1 into s. i.e, *(s+0)=*(s1+0) not the entire string. So we need to assign the address of s1 to s. i.e, s=s1.
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int main()
{
char *s = "abcdefghijklmnop", *s1=malloc(17);
int i;
for(i=0;i<strlen(s);i++)
{
*(s1+i) = *(s+strlen(s)-1-i);
}
s=s1;
printf("%s",s);
free(s1);
return 0;
}
It is good practice to free the memory after its use.

How to copy array value to another array

I have two arrays:
char roundNames1[16][25], roundNames2[16 / 2][25];
I then want to copy a result from the first array to the second. I have tried this:
where roundNames1[5] = "hello"
#include <string.h>
printf("First array: %s", roundNames1[5]);
strcpy(roundNames1[5], roundNames2[6]);
printf("Second array: %s", roundNames2[6]);
But this just returns
First array: hello
Second array:
Why is it not working?
You need to exchange arguments of function strcpy
strcpy( roundNames2[8], roundNames1[5] );
Here is a part pf the function description from the C Standard
7.23.2.3 The strcpy function
Synopsis
1
#include <string.h>
char *strcpy(char * restrict s1, const char * restrict s2);
Description
2 The strcpy function copies the string pointed to by s2 (including
the terminating null character) into the array pointed to by s1. If
copying takes place between objects that overlap, the behavior is
undefined.
strcpy - arguments other way around.
http://www.cplusplus.com/reference/cstring/strcpy/
Copy arrays/strings with memcpy
void * memcpy (void * destination, void * source, size_t size)
The memcpy function copies an certain amount of bytes from a source memory location and writes them to a destinaction location. (Documentation)
Example:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main()
{
char some_array[] = "stackoverflow";
int memory_amount = sizeof(some_array);
char *pointer = malloc(memory_amount);
memcpy(pointer, &some_array, memory_amount);
printf("%s\n", pointer);
free(pointer);
return 0;
}
Output
$ ./a.out
stackoverflow

Why this program is crashing did i wrongly allocated memory

This program is crashing. Please tell me what's wrong with it. When I use an array instead of a pointer like Name[12] in the structure it doesn't crash. I guess there is some problem in dynamic memory allocation. Help please.
#include <stdio.h>
struct struct_tag
{
int number;
char *Name;
} struct_name;
main()
{
struct_name.number = 34;
char *Name = (char *) malloc(sizeof(char));
strcpy(struct_name.Name,"A");
printf("%d", struct_name.number);
}
You're allocating a single character:
char *Name = (char *) malloc(sizeof(char));
And then never using that memory for anything. You meant to allocate memory for struct_name.Name, undoubtedly. But even if you had done so, you're then filling it with two characters ('a' and '\0'):
strcpy(struct_name.Name,"A");
which will cause an entirely different bug.
You want to say:
struct_name.Name = malloc( 2 );
Since (a) you shouldn't cast the result of malloc() and (b) sizeof(char) is always 1 and (c) you need room for the 0 at the end of your string.
For errors:
You are allocating memeory for *Name however you are not allocating
memory for struct_name.Name. So first thing is you need to allocate memory for struct_name.Name
As you already know that you'll be storing "A" in
struct_name.Name you should allocate memory for 2 char.("A" is string i.e 'A' and '\0')
For warnings:
If you want to use strcpy function include string.h in your code.
Also if you are using malloc include stdlib.h in your code.
Try this fixed code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct struct_tag
{
int number;
char *Name;
}struct_name;
int main()
{
struct_name.number = 34;
struct_name.Name = malloc(sizeof(char)*2); // As you will store "A"
strcpy(struct_name.Name,"A");
printf("%d \t", struct_name.number);
printf("%s \n", struct_name.Name);
return 0;
}
first look code carefully.
char *Name = (char *) malloc(sizeof(char));
strcpy(struct_name.Name,"A");
Hare for what you allocated memory (char *Name) and in which you copied string(struct_name.Name)?
here you not allocate memory for struct_name.Name. Also you have allocate memory for one character and you tried to copy two characters.('A' and '\0').
It should be
struct_name.Name = malloc(2);

Simple function using C pointers

I have the next code and I don't understand the pointer to pointer assignment in "dest" variable. Could someone please explain the meaning of this code?
#include <string.h>
#include <stdlib.h>
int main(void){
char s1[] = "012345678";
char dest;
dest = *(char * ) malloc(strlen(s1));
}
Thank you
This code doesn't make sense. It uses malloc to allocate memory of size 9, and then puts the first character of that allocated memory into dest. The problem is that the first character of the allocated memory can be anything, since allocated memory is not guaranteed to be initialized.
The statement
dest = *(char * ) malloc(strlen(s1));
will invoke undefined behavior.
C11: 3.4.3
1 undefined behavior
behavior, upon use of a nonportable or erroneous program construct or of erroneous data,
for which this International Standard imposes no requirements
You are trying to dereference the uninitialized malloced memory.
I guess your intention is to assign a pointer to the string buffer or you may want to allocate memory then copy s1 into the newly allocated memory. The following is the right way.
#include <string.h>
#include <stdlib.h>
int main(void)
{
char s1[] = "012345678";
char *dest0 = s1; // assign the address of s1 to dest0
char *dest1= malloc(sizeof(s1)); // allocate memory to dest1
strcpy(dest1, s1); // copy the string from s1 to dest1
}
you need to change char dest; by char *dest; and verify if char dest != NULL afer using malloc.
you can use strcpy to copy s1 "012345678" ===> in dest.

Resources