Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
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
Closed 9 years ago.
Improve this question
What is difference between the following code?
1.
char *p;
strcpy(p,"String");
2.
char *p;
p = "String";
The pointer points to the same string, but is there any difference?
In order for the first operation to work, p must point to a writable block of memory at least 7 bytes in size. The second operation does not require it.
After the first operation the string remains writable: you can do this on the first string, but not the second:
*p= 's'; // Make the value all lowercase
The second pointer assignment points p to a memory of a string literal; writing to that memory is undefined behavior.
(1) is a memory scribble and possibly a runtime error.
You cannot copy into memory you don't own (haven't allocated in some way).
In the first point you say you want to copy the string to the memblock p is pointing to
(so you have to make sure, there is enough space where the string can be copied to)
In the second case you just make p pointing to the read only address of "String".
p -> [S][t][r][i][n][g][0]
But you should get compiler warnings as far you don't declare p as p const *
Related
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
We don’t allow questions seeking recommendations for books, tools, software libraries, and more. You can edit the question so it can be answered with facts and citations.
Closed 6 years ago.
Improve this question
I've been trying to solve the "MIME type" puzzle from this site: https://www.codingame.com/games/puzzles/
And I've found an answer to this puzzle on the following site:
http://ethiery.vvv.enseirb-matmeca.fr/CGsolo/mime-type.html
Can somebody explain what the p = d.elmts+i; (line 49) from the above link does?
Why doesn't it work when I omit the 49th line and use this code in the subsequent lines instead? (It does not show an error till I try to print the ext and mimes using the d.elmts[i].ext/mime). It works like a charm when I use the p = d.elmts+i;.
(First time on stackoverflow. I'm not sure if this'll appear as a code snippet. Apologies if it doesn't)
Code
d.elmts[i].ext = malloc(11*sizeof(char));
d.elmts[i].mime = malloc(51*sizeof(char));
scanf("%s %s\n",d.elmts[i].ext, d.elmts[i].mime);
p is a pointer to a structure - this means that p 'holds' the starting address for a structure in memory --
Hence: p = d.elmts+i represents the starting address in memory, for the current structure (i represents the address offset).
In this example memory has been allocated for 'dictSize' structures (i.e. the number of structures).
Note that the memory for the structures is allocated contiguously (i.e.next to each other) and can therefore be easily accessed using the start address of the reserved memory (i.e. d.elemts) and some offset i.e. i
If a pointer to a a structure is declared then the underlying structure members can only can be accessed by the pointer when the arrow notation is used.
If a structure is declared (not a pointer to a structure) then the underlying structure members can be accessed using the dot notation.
using the '[]' notation in C - may be interpreted as trying to assigning an actual value (to memory that has been allocated) - whereas the pointer notation used in lines 50 and 51 is just enabling the allocating memory i.e. points to the start address of the memory being allocated - to hold possible values that each of the members may assume i.e. have not put values in this memory just yet - have to create/allocate memory first.
elmts is of datatype pair.
p = d.elmts+i;
This expression just assigns the next pair to p based on i. The pointer will be moved to the sizeof(pair) * i from elmts(Pointer arithmetic).
The pair contains the following 2 pointer members and you need to allocate memory before using them. That is what the next 2 lines do.
char *ext; char *mime;
If the pointer is not moved it will be pointing to the same pair.
The equivalent array expression for "p = d.elmts+i" is
p = &(d.elmts[i]);
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 7 years ago.
Improve this question
i would like to know if strdup adds a '\0' at the end of the new array if the src array does not contain one ?
let's assume we have an array containing "hello" allocated by this kind of malloc
malloc(sizeof(char) * 5);
so 5 bytes for 5 characters.
I guess the src string did not received the sufficient memory for the '\0'.
What is supposed to happen in this case ?
First the standard disclaimer: strdup isn't a standardized function, so exactly what it does could (at least in theory) vary from one compiler to the next. That said, every implementation I've seen of it has worked the same way.
strdup will determine the length of the input string--it'll start from the address in the pointer you pass, and find the first NUL byte after that location. Then it'll allocate a new block of memory and copy the bytes in that range to the newly allocated block.
So one of two things will happen. Either the input will contain a zero byte, and the result will too, or else strdup will read past the end of the input you passed, and you'll get undefined behavior (but chances are pretty good it'll find a zero byte eventually, and copy a bunch of extra garbage to the duplicate string).
One other minor note: if you use strdup, and then try to port you code to a compiler that doesn't define it, you might consider writing your own:
char *strdup(char const *s) {
size_t len = strlen(s) + 1;
char *ret = malloc(len);
if (ret != NULL)
strcpy(ret, s);
return ret;
}
That's obviously a pretty easy thing to do, but it has one other problem: including it in your code produces undefined behavior. You're not allowed to write a function with a name that starts with str. Those are all reserved for the implementation. So even though the function is simple and the behavior of its content is perfectly well defined, the mere existence of the function as a whole still gives undefined behavior.
What strdup() will do in this case is start with the string passed, and go on looking through memory until it either falls off the end of allocated memory (and you get a SIGSEGV or similar) or finds a byte that happens to contain a '\0'.
It will allocate enough memory to include a copy of everything it scanned, including the '\0', and then copy everything.
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
If I define char array like below
char arr[100] = "hello how are you";
where is this string("hello how are you") stored exactly? (stack/heap/data area/somewhere else?).
Stack Overflow vs stack crash
What is the difference between Stack Overflow and stack crash. When stack crash occurs?
Also heap overflow vs heap crash?
What happens when stack over flow/heap over flow occurs?
String literals are stored in read-only memory and persist for the length of the program. Thus it is safe to return this pointer from a function
.
const char *f()
{
return "Hello";
}
In your case, you copy the contents of the string literal into a local char array variable. So the storage of "hallo how are you" and char arr[100] are different.
You can modify arr and each time your program flow gets back to that line, arr will be initialized with the original string literal again. You can't return a pointer to arr from a function, because arr is only a local variable.
Tip: only char arr[] = "hallo how are you"; is necessary, unless you want to add more characters than are in your string literal.
I don't know what a "stack crash" is.
I'm not aware that heap can overflow. However, requests to allocate memory on the heap can fail. I don't know what a "heap crash" is.
When a stack overflow occurs, the program will typically crash. When a request to allocate heap memory fails, malloc will return NULL and new will throw std::bad_alloc
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I am getting Segmentation fault after return executes. Why is it coming after return and not in strcpy?
int main()
{
char a[2];
strcpy(a,"0123456789101112131415161718192021222324252627282930");
printf("%s\n",a);
return 0;
}
I am getting Segmentation fault after return executes. Why is it coming after return and not in strcpy?
You have made a common mistake called a buffer overflow. This results in undefined behavior, which is a standards answer. However, if you understand how a typical machine uses a stack, you can understand why it crashes when you return. Most CPUs use a down ward growing stack. So before you call strcpy, the stack is something like,
sp + 0 : a[0]
sp + 1 : a[1]
sp + 2 : padding
sp + 3 : padding
sp + 4: return address (four bytes)
The compiler machinery creates a call frame each time you use a function in 'C'. The return address exists as part of stack where the compiler allocates space for your a[] array. As it is under-sized for the string copy, you over-write the return address. This value isn't used until you return. The return address will be overwritten with something like the value 0x34353637 which is the binary pointer for the ASCII text '4567'.
It is advisable to use something like strncpy or an alternative. For example,
strncpy(a,"012345678...", sizeof(a));
a[sizeof(a)-1] = 0; /* ensure the string is terminated. */
Obviously you need to increase the size of your 'a' array if you want the full string to be printed.
Why is it coming after return and not in strcpy?
You get the segmentation fault when main returns because you overwrite critical data (saved frame pointer and return address) in the stack frame of main function and not in the stack frame of strcpy function.
As others already said, you invoke undefined behavior and anything can happen: from nothing to a nuclear war.
You're trying to load a string with a lot more than 2 characters into a char array that only holds 2 characters. This will cause a segmentation fault, since you are overwriting the memory allocated for the char array, which can also cause undefined behavior.
Your program overwrote the buffer, that would cause undefined behavior, which means literally anything could happen.
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions must demonstrate a minimal understanding of the problem being solved. Tell us what you've tried to do, why it didn't work, and how it should work. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I have the following code:
int *p;
p = (int*)malloc(sizeof(int) * 10);
but what is the default value of this int array with 10 elements? are all of them 0?
The real content is indeterminate.
C11, § 7.22.3.4 The malloc function
The malloc function allocates space for an object whose size is specified by size and
whose value is indeterminate.
However, the operating system often initializes this memory space to 0 (see this answer). You can use rather calloc to be sure that every bits are setted to 0.
are all of them 0?
No, malloc does not initialize the memory allocated, use calloc in order to initialize all values to 0
int *p;
p = calloc(10, sizeof(int));
It's undefined. Using calloc( ) instead then the allocated buffer is defined to be filled with binary 0
The "default" value of an element created with malloc is the value stored at this point in your memory (often 0 but you can have other values, if an another program wrote in this place).
You can use calloc, or after the malloc, you can memset your var.
And don't forget to verify the value of your pointer, check if it's not NULL.
You need to use calloc() for this purpose. malloc() allocats only memory, so this memory contains garbage values by default.