# help C, pointer



## graudeejs (Feb 22, 2009)

Hello!
I'm doing homework for university in C
I have actually finished it, but i have some questions.....

[already having problems expressing myself]
[i will generalize]


```
#include <stdlib.h>

void *create(void);

int main()
{
  unsigned char *ptr; /* my pinter, that will point to arry of text (unsigned char */
  ptr=create(); /* allocate memory */
}

void *create(void)
{
  unsigned char *new_ptr;
  new_ptr=malloc(1000);
...
  return new_ptr;
}
```

Is that correct (well it works)?

now i want to do the same, but this time i don't want create to return anything, i want it to work directly with pointer (if what i say makes sense)

can someone, plz, show me example how to do that?

EDIT:
I've just read another article....
Ok, i want to make it clear
I want a variable (or pointer)
then with create allocate memory and assign it to variable (pointer?)
i will later use that variable (pointer?) for other stuff to refer to allocated memory


----------



## Djn (Feb 22, 2009)

In order to do that, you would need to send the address of your pointer to the function.
Something like this (untested):

```
void main () {
  unsigned char *ptr;
  create(&ptr);
}

void create(unsigned char **ptr) {
  *ptr = malloc(1000);
}
```

Essentially, the function needs to know where to write the new address - and that's "the place in memory where the pointer is stored". If you read "&ptr" as "the address of ptr", and "unsigned char **ptr" as "a pointer to a pointer to an unsigned char", it's quite sensible.


----------



## graudeejs (Feb 22, 2009)

It seems to work....


```
#include <stdlib.h>
#include <stdio.h>

void create(unsigned char **ptr);

int main () {
  unsigned char *ptr;
  if (ptr==NULL) printf ("err\n");
    create(&ptr);
  if (ptr==NULL) printf ("err\n");
}

void create(unsigned char **ptr) {
  *ptr = malloc(1000);
}
```

i see 1 err, so i think it's good [now i will try to implement it and see if it really works]

p.s. ptr==NULL stuff works under pcc, however not under gcc.

btw maybe there is other way to do this?
because it was my idea that i need to define pointer in main... maybe i don't?


----------



## Djn (Feb 22, 2009)

Ah, good. I'm still slightly wary when doing any form of pointer handling. 

BTW, since you asked for English corrections in that other thread: A "seam" is the line where two things are joined together; you want "seem".


----------



## graudeejs (Feb 22, 2009)

here's my censored (simplified) function
it creates pascal like text string
**str is pointer to pointer
*txt is actual text to be inserted in pascal like string


```
void create(unsigned char [red]*[/red]*str, unsigned char *txt)
{
    unsigned int txt_len, tmp, i;

        tmp = txt_len = strlen(txt);
        [red]*[/red][color="Blue"]str = malloc(txt_max_len + txt_len_bytes);[/color]

// calculate and write down line lenght
        for (i=0; i<txt_len_bytes; i++) {
          [red]*[/red]str[i]=tmp % 256;
          tmp /= 256;
        }

// copy text
        for (i=txt_len_bytes; i<txt_len+txt_len_bytes; i++)
            [red]*[/red]str[i]=txt[i-txt_len_bytes];

// initialize rest of memory [not 100% necessary]
        while (i<txt_max_len+txt_len_bytes)
            [red]*[/red]str[i++]=0;
}
```

can you tell me what may cause segfault?
it was working when I used create to return pointer

i marked modified code red
blue makes segfault.... why?

txt_max_len and txt_len_bytes are predefined constants


----------



## fonz (Feb 22, 2009)

What exactly is it you're trying to do?

Seems to me that you're basically just trying to duplicate a string, which can be done in much simpler ways than this.

Alphons


----------



## graudeejs (Feb 22, 2009)

fonz said:
			
		

> What exactly is it you're trying to do?
> 
> Seems to me that you're basically just trying to duplicate a string, which can be done in much simpler ways than this.
> 
> Alphons



That is exactly that i need to do, but not in easier manner.
I need to dynamically allocate space for string (i choose to emulate pascal like stings, because it's little harder, than just using c stings) assign string vaues... and then program functions for it (find, cut.... etc)

It's homework in data structures....
i need to use pointers


----------



## Djn (Feb 22, 2009)

How do you call the create() function? It looks like the problem is the contents of **ptr.

Fonz: A pascal string is unterminated, but contains the string length before the first character. He's trying to create one of those from a C string.


----------



## graudeejs (Feb 22, 2009)

```
unsigned char *ptr;
create(&ptr, "text");
```

if you want/need, i can show code that actually works (create which returns pointer)


----------



## fonz (Feb 22, 2009)

killasmurf86 said:
			
		

> can you tell me what may cause segfault?
> it was working when I used create to return pointer
> 
> i marked modified code red
> ...



Are you sure it's the blue line that's causing the segfault?
I ran the following simplification and it works just fine:

```
#include <stdlib.h>

void
foo(unsigned char **ptr)
{
  *ptr=(unsigned char*)malloc(123*sizeof(unsigned char));
}

int main(int argc,char **argv)
{
  unsigned char *pointer;
  
  foo(&pointer);
  return 0;
}
```
Just a hunch, but I think it's the red stuff. Have you tried (*str)_ instead of *str? Remember that [] takes precedence over unary *.

Hope this helps,

Alphons_


----------



## graudeejs (Feb 22, 2009)

fonz said:
			
		

> Are you sure it's the blue line that's causing the segfault?
> I ran the following simplification and it works just fine:
> 
> ```
> ...


_

yes, I commented out everything else, I'll check your code_


----------



## fonz (Feb 22, 2009)

killasmurf86 said:
			
		

> yes, I commented out everything else, I'll check your code



That's odd. From my experience, malloc() itself is highly unlikely to cause segfaults. The culprit is usually something you do afterwards.

Let me know what happens when you try my code.

Alphons


----------



## graudeejs (Feb 22, 2009)

ok, that worked, now it break on second step...
i need to write to the allocated space.... from same function...
when i try, i get segfault


----------



## fonz (Feb 22, 2009)

That's probably the (*str)_ vs. *str thing I mentioned earlier. Tried that yet?

Alphons_


----------



## graudeejs (Feb 22, 2009)

fonz said:
			
		

> That's probably the (*str)_ vs. *str thing I mentioned earlier. Tried that yet?
> 
> Alphons_


_

doesn't seem to work (tried many different flavors. lol)

EDIT:
It does work on gcc,
on pcc it also works, but somewhere error is generated, and when main ends ... it's being showed

I prefer pcc for this, because it supports comparing ptr==NULL, unlike gcc
pcc sets newly defined pointer to NULL

EDIT:
pcc generates err, but doesn't exit

EDIT:
i can hide it by adding return 0 in main;_


----------



## fonz (Feb 22, 2009)

Can you post the exact code you have now? Then I can try to compile and run it on my system to see what it does.

Alphons

Edit: I don't know much about pcc, so I can't help you with that.


----------



## graudeejs (Feb 22, 2009)

here it is
http://killasmurf86.lv/data/download/main.c.bz2
comments are in my native


i commented few lines in create()
because they aren't supported in GCC


there might be other bad lines for gcc....

sorry for ugly code
i'm messing with it entire day


----------



## fonz (Feb 22, 2009)

The following code compiles and runs with both gcc and pcc (I ditched most of the comments), so the problem must be in some other function than create():
http://www.xs4all.nl/~zoefsam/fonz/smurf.c

Alphons


----------



## graudeejs (Feb 22, 2009)

remove:
return 0;
and compile with pcc, and then run it
otherwise it's fine


----------



## mjguzik (Feb 23, 2009)

If you don't return (insert some value here) in main, some random value is used and that's why 'an error is generated'. (Not only with pcc, with gcc too.) Your '(*str) == NULL' expression doesn't work as expected because afair the standard does not require local variables to be initialized. (Read as: *str is equal to some random value.) Initialize it explicitly to NULL and it will work.

Compile this code with -Wall to see scary things.


----------



## Djn (Feb 23, 2009)

I like using -Wall -ansi (and possibly -pedantic) when I'm not entirely sure if what I'm doing is a good idea. Warnings are good for you. (Note that -ansi doesn't allow // as a comment delimiter, at least not unless you compile as C99.)

Oh, and I quite like the TenDRA compiler (tcc); it's got very good warning/error messages.


----------



## fonz (Feb 23, 2009)

mjguzik said:
			
		

> afair the standard does not require local variables to be initialized. (Read as: *str is equal to some random value.)



That is correct.

*Global* _(also called external in K&R terminology)_ variables are initialized to zero by default (i.e. when not explicitly initialized), as are *static* variables. And it's ok to depend on that. It may be considered bad style, but it *is* technically correct. *Local* _(also called automatic in K&R terminology)_ variables on the other hand have undefined values when not explicitly initialized. If I'm not mistaken, compilers are free to initialize those to zero too, but that should really *not* be depended upon if you desire any degree of portability.

Of course, the easiest way to avoid problems is to just always explicitly initialize your variables 



			
				mjguzik said:
			
		

> Compile this code with -Wall to see scary things.


Not scary, educational 

Enabling warnings is often a good idea because it may point out dubious constructions and/or things that, although syntactically correct, just don't mean what's intended. Occasionally running Lint will also help you writing clean code :stud

Alphons


----------



## hydra (Feb 23, 2009)

I always compile my code with -Wall, it's really helpful sometimes. Static or automatic variables, always initialize the value !

OK:

```
int p;

p = f();
if(p == 0)
```

NOT OK:

```
int p;

if(p == 0)
```

If you run i386, be sure to check out devel/valgrind, it helps a lot !


----------



## mart (Feb 25, 2009)

http://cslibrary.stanford.edu/102/

and

http://cslibrary.stanford.edu/ in general, might help if you're just getting started.


----------

