I'm new to C and having trouble wrapping my head around double pointers and keep getting segmentation fault errors. I've debugged the program a bit and located where things go wrong, but can't for the life of me figure out why. I'll post my code first:
int main() {
printf("Enter string to be split: \n");
a = readline();
String *st = newString(a);
String **split;
int num;
num = string_split(st, ',', split);
for (i=0; i<num; i++) { print_string(*(split+i)); }
}
readline() produces a pointer to an array of chars (entered by the user) and appends '\0' to it. newString and print_string definitely work. Here's the struct for string:
typedef struct {
char *chars;
int length;
int maxSize;
} String;
And here is the code for string_split which is causing me all this trouble.
int string_split(String *s, char delim, String **arrayOfStructs) {
char *c = getCharacters(s);
int len = length(s);
int begin = 0;
int end;
int arraycount = 0;
String **temp = (String**)malloc(sizeof(String*));
for (end=0; end<len+1; end++) {
if ((*(c+end) == delim || *(c+end) == '\0') && begin != end) {
String *st = substring(s,begin,end-1);
*(temp + arraycount) = st;
begin = end + 1;
arraycount++;
temp = (String**)realloc(temp, 1+arraycount*sizeof(String*));
}
}
arrayOfStructs = temp;
return arraycount;
}
In main, when I get back split, all the String*'s that it points too are gone. When print_string gets an individual String* and tries to grab one of its members, a segmentation fault occurs. I don't understand why, because I feel like I allocate memory every time it is necessary, but I feel like I'm missing something. Also, when debugging, if I step through string_split, temp is produced exactly like I expect, so I think I'm just not malloc'ing somewhere where I'm supposed to and it's not a problem with the logic of the function. Here is the code in substring, although I'm pretty sure it works since I've been able to return String* from substring and pass them to print_string just fine.
String *substring(String *s1, int begin, int end) {
String *s = (String*)malloc(sizeof(String));
int length = 0;
s->maxSize = 20;
char *temp = (char*)malloc(20*sizeof(char));
char *arr = s1->chars;
int i;
for (i=begin; i <= end; i++) {
*(temp+length) = *(arr+i);
length++;
if (length == s1->maxSize-1) {
s1->maxSize = s1->maxSize+20;
temp = (char*)realloc(temp, s1->maxSize*sizeof(char));
}
}
*(temp+length) = '\0';
s->length = length;
s->chars = temp;
return s;
}
Any help is greatly appreciated!
You need to pass the argument arrayOfStructs by reference and not by value. As C doesn't actually have proper references, you have to pass a pointer to the variable:
int string_split(String *s, char delim, String ***arrayOfStructs) {
...
*arrayOfStructs = temp;
return arraycount;
}
Call it using the address-of operator &:
num = string_split(st, ',', &split);
As it is now, you pass the argument by value, which means that the variable arrayOfStructs is just a local copy inside the function. Any changes to it is only made to the copy, and are lost once the variable goes out of scope when the function returns.
String **temp = (String**)malloc(sizeof(String*));
*(temp + arraycount) = st;
temp+arraycount is going to give you a random address in memory. temp contains the pointer you just malloced, which should point to another pointer.(which you have not initialised), but you are incrementing the pointer so you loose the location you just malloced.
temp is not pointing to consecutive memory, it specifically points to another pointer(which is 8bytes on a 64bit machine)
Related
I have a strtok implementation (sort of), but it doesn't print the token!
char *tokenizer(char s[], const char *delimiter) {
char *p; //return value of function
int i = 0;
while(s[i] != *delimiter) //to get the size of array just right
i++;
char arr[i+1];
p = arr; //can't return an array, so assigned to a
//pointer
int j = 0;
i = 0;
while(s[i]!=*delimiter) {
arr[j] = s[i];
i++;
j++;
}
arr[j] = '\0';
printf("%s\n",p); //this statement works, but if excluded
//main prints nothing.
return p;
}
This function is being called as following, from the main:
char s[] = "tab-tab";
const char del[2] = "-";
char *p;
p = tokenizer(s, del);
printf("%s\n", p); //prints nothing without the printf in
//tokenizer
I tried debugging with gdb, and inspected the values of local variable after each line. p is updated with arr[j] inside tokenizer but goes to zero as soon as tokenizer finishes and frame shifts back to main.
The value ofp in main doesn't become NULL, it becomes an empty string, and prints that!
However, p in main prints the token if printf in tokenizer is included.
This already includes work-around. I know this can't possibly be the way strtok is implemented. I started with a more sophisticated, "expertish" version which had pointers, but couldn't get it to work, so settled for this "beginner" version.
It's because your pointer is pointing to a memory address in the stack, once your function is returned the memory address being pointed to no longer exists, you need to create dynamically allocated memory to access the variable outside of the function. The beauty of C
char *tokenizer(char s[], const char *delimiter) {
char *arr;
int i = 0;
while(s[i] != *delimiter)
i++;
// Initialize variable in the heap
if (!(arr = malloc(sizeof(char *) * (i+1))))
return NULL;
// Clear the array
bzero(arr, (i+1));
int j = 0;
i = 0;
while(s[i]!=*delimiter) {
arr[j] = s[i];
i++;
j++;
}
arr[j] = '\0';
// return pointer
return arr;
}
You should make sure to free the memory in the main to prevent memory leaks.
So I've looked around on SO and can't find code that answers my question. I have written a function that is supposed to reverse a string as input in cmd-line. Here is the function:
void reverse (char string[]) {
int x;
int i = 0;
char line[strlen(string)];
for (x = strlen(string) - 1; x > 0; x--) {
char tmp = string[x];
line[i] = tmp;
i++;
}
string = line;
}
When I call my reverse() function, the string stays the same. i.e., 'abc' remains 'abc'
If more info is needed or question is inappropriate, let me know.
Thanks!!
You're declaring your line array one char shorter remember the null at the end.
Another point, it should be for (x = strlen(string) - 1; x >= 0; x--) since you need to copy the character at 0.
void reverse (char string[]) {
int x;
int i = 0;
char line[strlen(string) + 1];
for (x = strlen(string) - 1; x >= 0; x--) {
char tmp = string[x];
line[i] = tmp;
i++;
}
for(x = 0; x < strlen(string); x++)
{
string[x] = line[x];
}
}
Note that this function will cause an apocalypse when passed an empty string or a string literal (as Bobby Sacamano said).
Suggestion you can probably do: void reverse(char source[], char[] dest) and do checks if the source string is empty.
I think that your answer is almost correct. You don't actually need an extra slot for the null character in line. You just need two minor changes:
Change the assignment statement at the bottom of the procedure to a memcpy.
Change the loop condition to <-
So, your correct code is this:
void reverse (char string[]) {
int x;
int i = 0;
char line[strlen(string)];
for (x = strlen(string) - 1; x >= 0; x--) {
char tmp = string[x];
line[i] = tmp;
i++;
}
memcpy(string, line, sizeof(char) * strlen(line));
}
Since you want to reverse a string, you first must decide whether you want to reverse a copy of the string, or reverse the string in-situ (in place). Since you asked about this in 'C' context, assume you mean to change the existing string (reverse the existing string) and make a copy of the string in the calling function if you want to preserve the original.
You will need the string library
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
Array indexing works, and this version takes that approach,
/* this first version uses array indexing */
char*
streverse_a(char string[])
{
int len; /*how big is your string*/
int ndx; /*because 'i' is hard to search for*/
char tmp; /*hold character to swap*/
if(!string) return(string); /*avoid NULL*/
if( (len=strlen(string)) < 2 ) return(string); /*one and done*/
for( ndx=0; ndx<len/2; ndx++ ) {
tmp=string[ndx];
string[ndx]=string[len-1-ndx];
string[len-1-ndx]=tmp;
}
return(string);
}
But you can do the same with pointers,
/* this is how K&R would write the function with pointers */
char*
streverse(char* sp)
{
int len, ndx; /*how big is your string */
char tmp, *bp, *ep; /*pointers to begin/end, swap temporary*/
if(!sp) return(sp); /*avoid NULL*/
if( (len=strlen(bp=sp)) < 2 ) return(sp); /*one and done*/
for( ep=bp+len-1; bp<ep; bp++, ep-- ) {
tmp=*bp; *bp=*ep; *ep=tmp; /*swap*/
}
return(sp);
}
(No, really, the compiler does not charge less for returning void.)
And because you always test your code,
char s[][100] = {
"", "A", "AB", "ABC", "ABCD", "ABCDE",
"hello, world", "goodbye, cruel world", "pwnz0r3d", "enough"
};
int
main()
{
/* suppose your string is declared as 'a' */
char a[100];
strcpy(a,"reverse string");
/*make a copy of 'a', declared the same as a[]*/
char b[100];
strcpy(b,a);
streverse_a(b);
printf("a:%s, r:%s\n",a,b);
/*duplicate 'a'*/
char *rp = strdup(a);
streverse(rp);
printf("a:%s, r:%s\n",a,rp);
free(rp);
int ndx;
for( ndx=0; ndx<10; ++ndx ) {
/*make a copy of 's', declared the same as s[]*/
char b[100];
strcpy(b,s[ndx]);
streverse_a(b);
printf("s:%s, r:%s\n",s[ndx],b);
/*duplicate 's'*/
char *rp = strdup(s[ndx]);
streverse(rp);
printf("s:%s, r:%s\n",s[ndx],rp);
free(rp);
}
}
The last line in your code does nothing
string = line;
Parameters are passed by value, so if you change their value, that is only local to the function. Pointers are the value of the address of memory they are pointing to. If you want to modify the pointer that the function was passed, you need to take a pointer to that pointer.
Here is a short example of how you could do that.
void reverse (char **string) {
char line = malloc(strlen(*string) + 1);
//automatic arrays are deallocated once the function ends
//so line needs to be dynamically or statically allocated
// do something to line
*string = line;
}
The obvious issue with this is that you can initialize the string with static memory, then this method will replace the static memory with dynamic memory, and then you'll have to free the dynamic memory. There's nothing functionally wrong with that, it's just a bit dangerous, since accidentally freeing the string literal is illegal.
char *test = "hello";
reverse(test);
free(test); //this is pretty scary
Also, if test was allocated as dynamic memory, the pointer to it would be lost and then it would become a memory leak.
EDIT: I should add how I have this all set up. The struct definition and prototypes are in mystring.h. The function definitions are in mystring.c. The main is in mystringtest.c. For mystring.c and mystringtest.c, I have #include "mystring.h" at the top. I'm compiling like gcc -o test.exe mystring.c mystringtest.c. Not sure if any of that matters, but I'm new with C so I'm just trying to include everything.
I have a good deal of experience with Java but am pretty new to C. I imagine this is related to pointers and memory but I'm totally at a loss here for what's going on. Here's my code:
typedef struct {
char *chars;
int length;
int maxSize;
} String;
int main() {
char *a;
a = readline();
String *s = newString(a);
int b = length(s);
printf("length is %d \n", b);
}
I run the program and enter "hello" (as prompted by readline()). I've stepped through the program and after length(s), s->chars is still a pointer to the array of chars 'hello'. After the print statement, s->chars becomes a pointer to the array of chars 'Length is %d \n'. I'm totally at a loss for what I'm doing wrong. I'm working on a virtual machine if that matters at all. Any help is greatly appreciated. I'll give the code for newString and length too.
int length(String *s) {
char *temp = s->chars;
char b = *temp;
int count;
if (b == '\0') { count = 0; }
else { count = 1; }
while (b != '\0') {
b = *(temp+count);
count++;
}
return count;
}
String *newString(char *s) {
String st;
st.length = 20;
st.maxSize = MAXCHAR;
char *temp = malloc(20 * sizeof(char));
char b = *s;
int count = 0;
while (b != '\0') {
*(temp + count) = b;
count++;
b = *(s+count);
if (count == st.maxSize) { break; }
if (count == st.length) {
st.length = st.length + 20;
temp = realloc(temp, st.length * sizeof(char));
}
}
st.chars = temp;
return &st;
}
String *newString(char *s) {
String st;
...
return &st;
}
You are returning a pointer to a local variable. After newString returns, the local variable no longer exists, so you have a dangling pointer.
Either allocate st with malloc, or return it by value.
you must null terminate the string after the while loop, you have not left space for the null terminator. Also I don't see why you need to realloc
//using strlen will eliminate the need for realloc, +1 is for the null terminator
int len = strlen(s)
char *temp = malloc((len * sizeof(char)) +1);
//null terminate
*(temp+count) = '\0';
st.chars = temp;
I have this function, bits_show, which prints to stdout a 2-3 bit long code.
void bits_show(bits *a)
{
int i;
for (i = 0; i < a->next; i++)
putchar(a->bits[i]);
}
where bits:
struct bits {
int capacity;
int next;
char *bits;
};
I am trying to write a function, char* bits_char(bits a) that captures these characters and collects them into a single char file.
This is what I have so far, but it keeps spitting errors:
char* bits_char(bits *a)
{
char* str = (char*) malloc( sizeof(a->next * char));
int i;
for (i=0; i<a->next; i++){
str[i] = (a->bits[i]);
}
return str;
}
"bits.c: In function ‘bits_char’:
bits.c:33: error: variable-sized object may not be initialized
bits.c:37: warning: function returns address of local variable"
This is wrong:
sizeof(a->next * char)
I presume you meant to write:
a->next * sizeof(char)
But since sizeof(char) equals 1 by definition you would simply omit that.
But even that is wrong since you need to allow space for the null terminator which your code does not currently write. The allocation needs to be:
malloc(a->next+1)
And add the null-terminator like this:
str[a->next] = 0;
All in all, the finished product is as so:
char* bits_char(bits *a)
{
char* str = malloc(a->next+1);
int i;
for (i=0; i<a->next; i++){
str[i] = (a->bits[i]);
}
str[a->next] = 0;
return str;
}
I removed the cast of the return value of malloc which is not needed in C.
And you should also ensure that you check the return value of malloc for a failed allocation. It will return the null pointer if it fails. I've not shown how to do that because I don't know your error handling policy.
to copy at the correct place but doesn't stop after the count is reached. I thought my code should work as follows
char har *orig, int start, int count, char *final);
int main(void)
{
const char source[] = "one two three";
char result[] = "123456789012345678";
printf("%s\n",GetSubstring(source, 4, 3, result));
return 0;
}
char r *orig, int start, int count, char *final)
{
char *temp = (char *)orig;
final = temp;
}
for ( ; *temp && (count > 0) ; count--)
{
rn final;
}
The first for loop doesn't check if temp array exists (how would it check for existence of an allocated memory without asking memory manager in some way?!). The temp is merely a pointer. What you're checking for is that the orig string doesn't have a zero within the first start bytes. That's OK, perhaps' that's what you meant by "existence".
Your intention is to copy from orig to final, yet you reset final to orig. That's where your error is. You must remove that line and it fixes the problem.
You don't need to create the temp pointer, you can use the orig pointer. You're free to modify it -- remember, function arguments are in effects local variables. Function arguments in C are pass-by-value, you implement pass-by-reference by passing pointers (which are values!) to data.
I should add perhaps that the premise of this function is somewhat broken. It "works", but it's not what one might reasonably expect. Notably:
There's no indication that the source string was shorter than start.
There's no indication that the source string was shorter than start + count.
Perhaps those are OK, but in cases where those conditions could be an error, it should be possible for the user of the function to get an indication of it. The caller would know what's expected and what's not, so the caller can determine it if only you'd provide some feedback to the caller.
You're returning the position that's one past the end of the output -- past the zero-termination. That's not very convenient. If one were to use the returned value to concatenate a subsequent string, it'd have to be decremented by one first.
Below is the fixed code, with sanely named variables.
char *GetSub(const char *src, int start, int count, char *dst)
{
for ( ; *src && (start > 0) ; start--)
{
src++; /* Note: *src++ works too, but is pointless */
}
for ( ; *src && (count > 0) ; count--)
{
*dst++ = *src++;
}
*dst++ = 0;
return dst; /* Notice: This returns a pointer to the end of the
memory block you just wrote. Is this intentional? */
}
There are several problems in what you have written. Let's enumerate:
char *temp = (char *)orig; - You're assigning a const char * (you promise not to modify) to a char * (you break that promise). Wrong thing to be doing.
final = temp. No this does not make the original final (the copy held by the caller) change at all. It achieves nothing. It changes your (function's) copy of final to point to the same place that temp is pointing.
*temp++; - There's no point de-referencing it if you're not going to use it. Incrementing it of course, is correct [see comment thread with KubaOber below].
final++ = *temp++; - This is just confusing to read.
*final++ = 0; return final; - You're setting the value at the address final to '0'. Then you're incrementing it (to point to somewhere in space, maybe towards a black hole). Then returning that pointer. Which is also wrong.
What you really should do is to wrap strncpy in a convenient way.
But if you insist to write your own, you'd probably want your function to be something as simple as:
char *GetSub(const char *orig, int start, int count, char *final)
{
int i;
for (i = 0; i < count; i++)
{
final[i] = orig[i+start];
if (final[i] == '\0')
break;
}
final[i] = '\0';
return final; /* Yes, we just return what we got. */
}
The problem is with the following line:
final = temp;
Remove it, and the problem should be resolved.
char *a="abcdefgh";
i want string "cde" to be copied into another.
index i got is 3(your start).
char *temp=malloc(3*sizeof(char))
strncpy(temp,a+3,3);
is this what you need?
Change your GetSubfunction:
char *GetSub(const char *orig, int start, int count, char *final)
{
char *temp = (char *)orig;
// with original final = temp and final++ you loose final valid pointer
char *final2 = final;
for ( ; *temp && (start > 0) ; )
{
start--;
// you don't need to dereference temp
temp++;
}
for ( ; *temp && (count > 0) ; count--)
{
*final2++ = *temp++;
}
*final2 = 0;
// return a valid pointer
return final;
}
you have some mistakes on your code :
char *GetSub(const char *orig, int start, int count, char *final)
{
char *temp = (char *)orig;
//final = temp; /* Why this? */
for ( ; *temp && (start > 0) ; )
{
start--;
temp++; /* Instead of *temp++ */
}
for ( ; *temp && (count > 0) ; count--)
{
*final++ = *temp++;
}
*(final+count) = '\0';
return final;
}
Hope this help.